/
calcPrices.js
34 lines (28 loc) · 1.08 KB
/
calcPrices.js
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
30
31
32
33
34
function addDecimals(num) {
return (Math.round(num * 100) / 100).toFixed(2);
}
// NOTE: the code below has been changed from the course code to fix an issue
// with type coercion of strings to numbers.
// Our addDecimals function expects a number and returns a string, so it is not
// correct to call it passing a string as the argument.
export function calcPrices(orderItems) {
// Calculate the items price in whole number (pennies) to avoid issues with
// floating point number calculations
const itemsPrice = orderItems.reduce(
(acc, item) => acc + (item.price * 100 * item.qty) / 100,
0
);
// Calculate the shipping price
const shippingPrice = itemsPrice > 100 ? 0 : 10;
// Calculate the tax price
const taxPrice = 0.15 * itemsPrice;
// Calculate the total price
const totalPrice = itemsPrice + shippingPrice + taxPrice;
// return prices as strings fixed to 2 decimal places
return {
itemsPrice: addDecimals(itemsPrice),
shippingPrice: addDecimals(shippingPrice),
taxPrice: addDecimals(taxPrice),
totalPrice: addDecimals(totalPrice),
};
}