javascript - 将组合折扣应用于食品订单
问题描述
一个应用程序允许用户从菜单中订购食物。菜单有三种选择:主菜、饮料和甜点。需要添加一项功能,该功能将为每个主+饮料组合折扣 10%(每个组合 10% 折扣)。客户订购的所有商品都存储在一个数组中,如下所示:
order = [
{id: 4, count: 1, type: "main", price: 10}
{id: 5, count: 2, type: "drink", price: 9.5}
]
如您所见,客户订购的每件商品都有一个计数属性。如何在不改变订单数组或任何对象属性的情况下应用折扣?理想情况下,我想遍历数组,确定组合的总数(在上面的示例中为 1),确定总折扣值并将该值传递给另一个计算订单总数的函数。如果有人可以提出更好的方法,我会全神贯注(在这种情况下是眼睛)。
另外,从技术角度来说,表达这个问题的最佳方式是什么?
解决方案
const userOrder = [
{ id: 4, count: 1, type: "main", price: 200 },
{ id: 5, count: 1, type: "drink", price: 100 }
];
const orderInfo = userOrder.reduce((acc, cur) => {
console.log('cur', cur)
if (acc[cur.type]) {
return {
...acc,
[cur.type]: cur.count,
totalAmount: (cur.count * acc.totalAmount)
}
} else {
return {
...acc,
[cur.type]: cur.count,
totalAmount: (cur.count * cur.price ) + acc.totalAmount
}
}
}, {
main: 0,
drink: 0,
totalAmount: 0
});
const noOfComobosPresent = Math.min(orderInfo.main, orderInfo.drink);
const totalDiscountValue = noOfComobosPresent * 10;
const finalAmount = orderInfo.totalAmount - ((orderInfo.totalAmount * totalDiscountValue ) / 100) ;
console.log('finalAmount', finalAmount)
推荐阅读
- spring - Spring OAuth2中的自定义登录和批准ui页面
- vim - 如何用冒号突出显示搜索字符串的第二部分?
- android - videoView 与 seekBar, seekTo 与 seekBar 进度
- javascript - 如何选择创建文本文件的目录
- kubernetes - 如何在 Kubernetes 的 cluster-cidr 中设置不同的(从默认值)掩码?
- php - 在 PHP 中实现并行 cURL 的最简单方法是什么?
- django - Django:访问多对多字段
- python - 如何在 PyQt4/5 中使用 HTTPS
- typescript - 在 Ionic 中使用 Md5 加密密码
- ios - React-Native 动画边框半径、宽度和对导航栏的粘性