I have a function whose task is to count the price of a product after a discount. However as a result I get objects without this value (totalPrice). Where am I making mistake?
const arrayObj = [
{
basePrice: 12,
discount: 3,
},
{
basePrice: 12,
discount: 2,
},
{
basePrice: 8,
discount: 2,
},
];
interface Product {
basePrice: number;
discount: number;
totalPrice?: number;
}
const countTotalPrice = (products: Product[]): Product[] => {
const calculateTotalPrice = (
basePrice: number,
discount: number,
totalPrice?: number
): void => {
totalPrice = basePrice - discount;
};
products.forEach((product) =>
calculateTotalPrice(
product.basePrice,
product.discount,
product.totalPrice
)
);
return products;
};
console.log(countTotalPrice(arrayObj));
You are not modifying products in your array. You have two options:
products.forEach and pass in a function that modifies a product. Return modified products.products.map and pass in a function that takes a product and creates new object with additional property, return the result of mapping.I would argue that 2nd approach is more idiomatic in JS/TS.
const countTotalPrice = (products: Product[]): Product[] => {
return products.map((product) =>
({ // the parentheses are necessary in this position
// we want object literal, not code block
...product,
totalPrice: product.basePrice - product.discount
})
);
}
Playground link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With