首页 > 解决方案 > 将组合折扣应用于食品订单

问题描述

一个应用程序允许用户从菜单中订购食物。菜单有三种选择:主菜、饮料和甜点。需要添加一项功能,该功能将为每个主+饮料组合折扣 10%(每个组合 10% 折扣)。客户订购的所有商品都存储在一个数组中,如下所示:

order = [
{id: 4, count: 1, type: "main", price: 10}
{id: 5, count: 2, type: "drink", price: 9.5}
]

如您所见,客户订购的每件商品都有一个计数属性。如何在不改变订单数组或任何对象属性的情况下应用折扣?理想情况下,我想遍历数组,确定组合的总数(在上面的示例中为 1),确定总折扣值并将该值传递给另一个计算订单总数的函数。如果有人可以提出更好的方法,我会全神贯注(在这种情况下是眼睛)。

另外,从技术角度来说,表达这个问题的最佳方式是什么?

标签: javascriptnode.jstypescript

解决方案


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)

推荐阅读