一个简单的购物车折扣逻辑
在购物车中遇到这样一个逻辑,商品加入购物车后,计算价格时需要考虑到一些促销活动,需求是让促销的金额最大化,并且每笔订单需要限制可以参与折扣商品的数量。实现思路就是每次在购物车加减商品时都需要计算一次每件商品的促销价格,并且保存到购物车中保存的每条商品数据中,购物车数据大致如下:
[{
name: "JavaScript从入门到入土",
maxQty:3,
discount:8, // 折扣力度(8折)
originPrice:30, // 原价
spuCode: "1909211603",
minQty: 1
},{
name: "JavaScript权威指南",
maxQty:3,
discount:5,
originPrice:60,
spuCode: "1909211603",
minQty: 1
},{
name: "从0开始学html+css3",
maxQty:3,
discount:8,
originPrice:60,
spuCode: "1909211603",
minQty: 1
},{
name: "杂牌笔记本电脑",
maxQty:3,
discount:9,
originPrice:500,
spuCode: "1909211603",
minQty: 1
}]
目前购买了四件商品,都参与了折扣,如果此时后台配置了每单限制打折商品为两件,此时就得判断到底是那两件参与打折,这个时候得先对数据进行处理,计算出折扣后价格和折扣力度
[{
name: "JavaScript从入门到入土",
maxQty:3,
discount:8, // 折扣力度(8折)
originPrice:30, // 原价
spuCode: "1909211603",
minQty: 1,
promotionInfo:{ // 计算好的折扣信息
currentPrice:24, // 折扣后价格
discountPrice:6 // 折扣力度(原价 - 折扣后价格)
}
},{
name: "JavaScript权威指南",
maxQty:3,
discount:5,
originPrice:60,
spuCode: "1909211603",
minQty: 1,
promotionInfo:{
currentPrice:30,
discountPrice:30
}
},{
name: "从0开始学html+css3",
maxQty:3,
discount:8,
originPrice:60,
spuCode: "1909211603",
minQty: 1,
promotionInfo:{
currentPrice:48,
discountPrice:12
}
},{
name: "杂牌笔记本电脑",
maxQty:3,
discount:9,
originPrice:500,
spuCode: "1909211603",
minQty: 1,
promotionInfo:{
currentPrice:450,
discountPrice:50
}
}]
这个时候就可以使用 sort 方法对购物车数据进行一个排序操作了,折扣力度大的放前面(通过 discountPrice 判断)
const sortshopCartList = shopCartList.sort((a, b) => b.promotionInfo.discountPrice - a.promotionInfo.discountPrice)
因为限制每单只能优惠两个,所以之后只要将 sortshopCartList 索引从2开始的每一条商品数据的价格恢复原价就好了
sortshopCartList.forEach((com,index) => {
if(index >= 2){ // 这里的是订单最大优惠数,应由接口获取
com.promotionInfo = {
currentPrice:com.originPrice,
discountPrice:0
}
}
})
最终处理完的购物车数据:
最后计算总价为:570
const totalPrice = sortshopCartList.reduce((acc, cur) => {
return acc + cur.promotionInfo.currentPrice
}, 0)