场景:需要计算经过满减,积分,红包处理后的最后的价格。
实现思路:定义三个方法,去改变全局的价格。巧妙使用数组的reduce方法实现。
代码:
/**
* 链式处理
* 外卖订单的总价计算
* 积分、红包、满减
*
*
*/
let orderInfo = {
total: 50
}
let actions = [pointHandle, redbagHandle, manjianHandle]
let action2=[manjianHandle,pointHandle, redbagHandle]
//arr.reduce(function(total,currentValue,currentIndex,arr),intialValue)
action2.reduce((newOrder, handle) => {
handle(newOrder)
return newOrder;
}, orderInfo)
console.log(orderInfo)
function pointHandle(order) {
// 积分换算
console.log('积分',order)
order.total = order.total - 10
}
function redbagHandle(order) {
// 红包换算
console.log('红包',order)
order.total = order.total - 5
}
function manjianHandle(order) {
// 满减换算
console.log('满减',order)
if(order.total>40){
order.total = order.total - 10
}
}
总结:这里的实现思路巧妙使用了数组的reduce方法。优点是:可以按照action2数组的元素(方法)顺序曲调用每个场景下的函数,得到最后的价格。代码精简,思路清晰,值得回味。
新学的东西,拿出来和大家探讨,一块进步呀!!!!!!