阶梯折扣算法实现需求:根据基础数量计算新增购品折扣
实现阶梯折扣计算的get_discounts方法方案
需求背景
用户已有一定基础商品数量,计划新增购买商品,现有如下阶梯折扣体系:
const b1 = { min: 1, max: 5, discount: 0.01 } const b2 = { min: 6, max: 10, discount: 0.02 } const b3 = { min: 11, max: 15, discount: 0.03 } const b4 = { min: 16, max: 20, discount: 0.04 } const discountTiers = [b1, b2, b3, b4] // 完整折扣体系
需要实现get_discounts方法,根据用户的基础商品数量和新增购买数量,返回新增商品对应的折扣详情(包括各阶梯的购买数量和对应折扣)。
实现思路
核心逻辑是把新增的购买量按阶梯拆分:
- 从用户当前的基础数量开始,依次匹配每个折扣阶梯
- 计算当前阶梯能容纳的新增数量上限,取“剩余新增量”和“阶梯上限剩余量”的较小值作为该阶梯的实际购买量
- 记录该阶梯的购买量和折扣,更新当前总数量和剩余新增量
- 处理完所有定义的阶梯后,如果还有剩余新增量,默认按0折扣处理(可根据实际需求调整)
完整代码实现
// 定义折扣阶梯 const b1 = { min: 1, max: 5, discount: 0.01 }; const b2 = { min: 6, max: 10, discount: 0.02 }; const b3 = { min: 11, max: 15, discount: 0.03 }; const b4 = { min: 16, max: 20, discount: 0.04 }; const discountTiers = [b1, b2, b3, b4]; function get_discounts(baseQty, addQty) { let currentTotal = baseQty; let remainingAdd = addQty; const discountDetails = []; for (const tier of discountTiers) { if (remainingAdd <= 0) break; // 计算当前阶梯可容纳的新增数量上限 const maxAvailableInTier = tier.max - currentTotal; if (maxAvailableInTier <= 0) continue; // 确定该阶梯实际购买的数量 const qtyInTier = Math.min(remainingAdd, maxAvailableInTier); discountDetails.push({ quantity: qtyInTier, discount: tier.discount }); // 更新状态 currentTotal += qtyInTier; remainingAdd -= qtyInTier; } // 处理超出所有阶梯的新增数量(默认折扣0,可按需修改) if (remainingAdd > 0) { discountDetails.push({ quantity: remainingAdd, discount: 0 }); } return discountDetails; } // 示例测试 // 示例1:基础数量5,新增3件 console.log(get_discounts(5, 3)); // 输出: [{ quantity: 3, discount: 0.02 }] // 示例2:基础数量5,新增6件 console.log(get_discounts(5, 6)); // 输出: [{ quantity: 5, discount: 0.02 }, { quantity: 1, discount: 0.03 }]
代码说明
- 函数返回一个数组,每个元素包含
quantity(该阶梯的新增购买量)和discount(对应折扣率),清晰展示新增商品的折扣分布 - 兼容跨阶梯的新增购买场景,比如从基础数量5新增6件时,会拆分到两个阶梯计算
- 超出定义阶梯的部分(比如新增后总数量超过20),默认按0折扣处理,你可以根据实际业务需求修改这部分逻辑
内容的提问来源于stack exchange,提问作者qg_java_17137
相关产品推荐
相关产品推荐

