# Example: Define a Custom Addition Function

This example takes in a set of item prices and stock amounts and uses several functions to calculate subtotals, deduct discounts and add taxes.

It makes use of the following:

• `map` function to go through all the items in the input.

• basic math operations like `*`, `+` and `-`.

• String concatenation with `++`.

• `as` to force string values into numbers.

• Fixed values in the header to set tax and discount amounts.

• A custom function in the header, to define once and use multiple times in the code.

• `reduce` function to aggregate the various items into a total.

DataWeave
``````

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

%dw 2.0
output application/json
var tax = 0.085
var discount = 0.05
fun getSubtotal (items) = items reduce ((item, accumulator = 0) ->
accumulator + (item.unit_price * item.quantity * (1 - discount)))
---
invoice: {
item : {
description: \$.description,
quantity: \$.quantity,
unit_price: \$.unit_price,
discount: (discount * 100) as Number ++ "%",
subtotal: \$.unit_price * \$.quantity * (1 - discount)
}
}) },
totals:
{
tax: (tax * 100) as Number ++ "%",
total: getSubtotal(payload.invoice.items ) * (1 + tax)
}
}

``````
Input JSON
``````

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

{
"invoice": {
"customer_name": "ACME, Inc.",
"customer_state": "CA"
},
"items": [
{
"description": "Product 1",
"quantity": "2",
"unit_price": "10"
},
{
"description": "Product 2",
"quantity": "1",
"unit_price": "30"
}
]
}
}

``````
Output
``````

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

{
"invoice": {
"customer_name": "ACME, Inc.",
"customer_state": "CA"
},
"items": {
"item": {
"description": "Product 1",
"quantity": "2",
"unit_price": "10",
"discount": "5.00%",
"subtotal": 19.00
},
"item": {
"description": "Product 2",
"quantity": "1",
"unit_price": "30",
"discount": "5.00%",
"subtotal": 28.50
}
},
"totals": {
"subtotal": 47.50,
"tax": "8.500%",
"total": 51.53750
}
}
}

``````