问题描述
任务是构建一个准确的价格计算器,根据数量计算销售价格。我已经使用compiledCart.reduce() 方法构建了一个总价计算器,(如下)但是我不知道如何添加销售功能。
如果用户购买 1 个 Candy,价格为 3.97 美元,如果用户购买 2 个,价格为 5.00 美元。 如果用户购买 3 个,那么前两个是 5.00 美元,第三个是 3.97 美元。如果用户购买 5 个也是一样。前 4 个是 10 美元,第 5 个是 3.97 美元
我的compiledCart变量如下所示:
[
0: {item: "candy",quantity: 3,price: 3.97,salesPrice: 5.00},1: {item: "bread",quantity: 1,price: 2.17}
]
这就是我正在做的事情:
const gross = compiledCart.reduce( ( sum,{ price,quantity } ) => sum + (price * quantity),0)
但我终生无法弄清楚如何将销售价格变量考虑在内。
我尝试使用模数 % 运算符,如下所示:
quantity % 2
但是,如果有提醒,它只会返回 1 或 0。因此,购物车中的 2 个糖果将返回 0,而 1 个糖果将返回 1,因为 1 / 2 = 1。但我不确定如何将其用于我的事业?
解决方法
如果数量大于 2,则:
将数量除以 2 再乘以 salesPrice
var compiledCart = [
{item: "candy",quantity: 3,price: 3.97,salesPrice: 5.00},{item: "bread",quantity: 1,price: 2.17}
];
var sum = compiledCart.reduce((sum,{ quantity,price,salesPrice = 0 }) => {
let tot = 0;
if (quantity > 1)
tot = Math.trunc(quantity / 2) * (salesPrice || price);
if (quantity % 2 == 1)
tot += price;
return sum + tot;
},0);
console.log(sum);
试试这个
const gross = cart.reduce((sum,{price,quantity,salesPrice = 0}) => {
let total = 0;
if (quantity >= 2) {
const saleQuantity = 2 * Math.floor(quantity / 2);
console.log({saleQuantity,remainderQuantity: quantity - saleQuantity});
total = ((saleQuantity / 2) * salesPrice) + (price * (quantity - saleQuantity));
} else {
total = (price * quantity);
}
return sum + total;
},0);