【问题标题】:Price Calculation Tool价格计算工具
【发布时间】:2020-05-26 15:23:06
【问题描述】:

我正在尝试制作一个价格计算工具。某些选项的减少有点复杂,我被困在如何将其转换为代码上。 有4种不同的产品: 产品 1:10 欧元 产品 2:20 欧元 产品 3:30 欧元 产品 4:40 欧元

对于产品 1 和产品 2,没有减少。

如果您购买 2 件或更多件产品 3,价格将降至 21 欧元。

如果您购买 2 件或更多的产品 4,价格将降至 31 欧元。

如果您同时购买产品 3 和产品 4,产品的价格将分别降至 21 欧元和 31 欧元。

你们能帮我看看我应该如何将它翻译成 javascript(或其他语言,如果你认为有更好的解决方案)?

非常感谢!

【问题讨论】:

  • 创建一个JSON对象,以所有产品为键,产品的数量应存储为相应的值。应用规则并根据它们获取值。返回总数
  • 如果将来产品 1 获得折扣会怎样?我的问题实际上是,作为前端程序员,您如何知道产品 1 是产品 1?
  • 给所有的产品一个唯一的ID来识别。将其存储在地图中。在结算时应用折扣

标签: javascript math calculator


【解决方案1】:

您可以为产品和价格对象/地图创建关系

在计算购物篮价格时,根据定义的规则更新产品价格。

let products = {
	p1: 10,
	p2: 20,
	p3: 30,
	p4: 40
}

let priceCalculate = (basket) => {
	let disPrices = { ...products }
	if (basket.filter(e => e === 'p3').length >= 2) disPrices.p3 = 21
	if (basket.filter(e => e === 'p4').length >= 2) disPrices.p4 = 31
	if (basket.includes('p3') && basket.includes('p4')) disPrices.p3 = 21, disPrices.p4 = 31
	return basket.reduce((a, b) => a + disPrices[b], 0);
}
let Mybasket = ['p1', 'p2', 'p3', 'p2', 'p3'];
console.log(priceCalculate(Mybasket))

【讨论】:

    【解决方案2】:

    使用对象来存储价格和价值

    var obj={P1:10,P2:20,P3:30,P4:40};
    var basket={P1:5,P2:4,P3:3,P4:8};
    var total=0;
    obj['P3']>=2?obj['P3']=21:false;
    obj['P4']>=2?obj['P4']=31:false;
    if(obj['P3']>=1 && obj['P4']>=1)
    {
    obj['P3']=21;
    obj['P4']=31;
    }
    Object.keys(basket).forEach(e=>{
    total+=basket[e]*obj[e];
    })
    console.log(total)
    Product 1: €10 Product 2: €20 Product 3: €30 Product 4: €40
    
    For Product 1 and Product 2 there is no reduction.
    
    If you buy 2 or more of Product 3, the price reduces to €21.
    
    If you buy 2 or more of Product 4, the price reduces to €31.
    
    If you buy Product 3 and Product 4 together, the price reduces to €21 and €31 for the products respectively.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多