定价折扣逻辑,4美元的价格为2美元,5美元的价格为6美元

问题描述

所以我目前正在研究一些情况下的定价逻辑:

  • 1副手套的价格为2.50美元,2副手套的价格为4美元,因此可享受20%的折扣。
  • 如果某人买了3副手套,则应该是$ 4 +原价$ 2.50,总计$ 6.50
  • 如果某人买了四副手套,则应该是$ 8。

  • 1颗口香糖的价格为0.65美元,您可以以5的价格购买6块胶,因此6块的价格为3.25美元,而不是3.90美元
  • 如果某人买入7,那么它应该是6,价格为$ 3.25 +原价$ 0.65,总计$ 3.90
  • 如果某人买入8,则应为$ 3.25 + 6(原始价格为$ 0.65 * 2),总计为$ 4.55,为6

因此,在哪个索引/阶段需要应用折扣非常重要

我从本文中汲取了逻辑灵感: http://codekata.com/kata/kata01-supermarket-pricing/

我从本文中获得了代码启发: https://github.com/raddanesh/Kata01

特别是如下图所示的VolumePricingStrategy:

enter image description here

鉴于我要实现的逻辑,这是我的代码尝试:

//2 for $4
const gloves = {quantity: 3,price: 2.50 }

function volumePricegloves(threshold = 2){
  let regularPrice = gloves.quantity * gloves.price;
  let volumediscount = 0;
    
  let volumePrice = regularPrice * 0.8;

  if(gloves.quantity >= threshold){
    volumediscount = threshold * gloves.price - volumePrice
  }
  return regularPrice - volumediscount;
}

// 5 for the price of 6
const gum = {quantity: 7,price: 0.65 }

function volumePriceGum(threshold = 6){
  let regularPrice = gum.quantity * gum.price;
  let volumediscount = 0;
  
  let volumePrice = regularPrice * 0.16666667;

  if(gum.quantity % threshold){
    volumediscount = threshold * gum.price - volumePrice;
  }
  
  return regularPrice - volumediscount; 
}

我的代码显然是错误的,因为它在调用函数输出不正确的值。虽然我非常喜欢github.com/raddanesh/Kata01编写的代码,并且可以理解其背后的概念。我真的很难真正理解volumePrice代表什么。在我看来,volumePrice是产品达到阈值时的折扣价。

因此,对于手套而言,将volumePrice设置为RegularPrice * 0.8表示合理,这表示原始价格有20%的折扣。但是,我的意图并没有在我的代码中完全体现出来VolumePricegloves(3)返回6而不是6.5,并且如果您更改阈值参数量,则所有方案都不匹配。任何想法/帮助都将不胜感激!

对于口香糖场景,我不确定github.com/raddanesh/Kata01的代码示例是否可以应用于此逻辑。似乎有很大的不同,我不确定真正采用哪种方法。 如您所见,我已经在这一个常规价格* 0.16666667上设置了volumePrice,这反映了每颗胶的折扣金额。

我想到的另一个想法可能是将价格放入数组中,并在达到阈值时弹出最后一个,但是我不确定我是否仍然需要数组中的商品进行进一步计算。我认为这是最棘手的问题,我在网上找不到很多很好的例子,因此这篇文章!欢迎所有想法/建议!

解决方法

这两种情况都需要大致相同的逻辑-有一个单独的价格和一个组价格,而任何不适合一个组的商品都将获得单独的价格。

因此,我的方法是仅将其用作逻辑的基础。编写一个将数量,组数量,单个价格和组价格作为输入的函数,如下所示:

function getPrice(qty,groupQty,indivPrice,groupPrice) {
  const groupCount = Math.floor(qty / groupQty);
  const indivCount = qty % groupQty;
  return (groupCount * groupPrice) + (indivCount * indivPrice);
}

console.log(getPrice(5,2,1.5,2.5)); // groups of 2 cost 2.5,but 1 costs 1.5 -- total should be 6.5

因此,从现在开始,您需要做的就是根据交易类型确定“ groupPrice”

,

有很多方法可以做到这一点。我倾向于走更少的代码。

我会走这条路线。

if(quantity => threshold){

discounteditems = Math.floor(quantity/threhold);
remainder = quantity%threhold;
discountedtotalprice = discounteditems * discountedprice;
fullprice = remainder * fullprice;

}

通过这种方式,您可以获得所有折扣商品,超出此阈值的部分将收取全价。

对我来说,这是一种获取所需欲望的简单方法。