【问题标题】:Apply Combo Discount to a Food Order将组合折扣应用于食品订单
【发布时间】:2021-05-02 09:55:31
【问题描述】:

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

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

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

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

【问题讨论】:

  • (order[0]['count']*order[0]['price']) + (order[1]['count']*order[1]['price']) - (Math.abs(order[0]['count']-order[1]['count'])*(order[0]['price']+order[0]['price'])*0.1) 第一个减号后面的部分是折扣,如果我理解你的问题的话。

标签: javascript node.js typescript


【解决方案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)

【讨论】:

  • 这是完全错误的。我们必须将价格乘以数量。组合的数量取决于一种饮料和主要的存在,而不是一种或另一种。另外我不确定你为什么要将折扣值乘以 10。
  • 我的错误,很好的捕获我错过了这些注意事项,现在我已经做出了更改,您可以在 ts playround 中测试它。关于discount value * 10 我这样做是因为一个组合是 10%,如果 2 个组合是 20%,依此类推......
猜你喜欢
  • 1970-01-01
  • 2011-10-23
  • 1970-01-01
  • 2016-01-22
  • 2020-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多