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));
CodePudding user response:
You are not modifying products in your array. You have two options:
- use
products.forEach
and pass in a function that modifies a product. Return modified products. - use
products.map
and pass in a function that takes a product and adds 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
})
);
}
CodePudding user response:
try this
const countTotalPrice = (products: Product[]): Product[] => {
const calculateTotalPrice = (
p:Product
): void => {
p.totalPrice = p.basePrice -p. discount;
};
products.forEach((product) =>
calculateTotalPrice(
product
)
);
return products;
};
CodePudding user response:
You can use Array.prototype.map() combined with Destructuring assignment:
interface Product {
basePrice: number;
discount: number;
totalPrice?: number;
}
const arrayObj: Product[] = [{ basePrice: 12, discount: 3 },{ basePrice: 12, discount: 2 },{ basePrice: 8, discount: 2 },];
const countTotalPrice = (products: Product[]): Product[] =>
products.map((p) => ({
...p,
totalPrice: p.basePrice - p.discount,
}));
Code example without TypeScript:
const arrayObj = [{basePrice: 12,discount: 3,},{basePrice: 12,discount: 2,},{basePrice: 8,discount: 2,},]
const countTotalPrice = (products) =>
products.map((p) => ({
...p,
totalPrice: p.basePrice - p.discount,
}))
console.log(countTotalPrice(arrayObj))