reduce方法介绍
开始之前先介绍下reduce函数的使用。reduce是数组的一个高阶方法,用来遍历数组的每一项实现累加
var arr = ['a','b','c'];
var str = arr.reduce((total, item) => total + item); //abc
total初始值默认为数组的第一项,还可以通过reduce的第二个参数给total设置初始值
var arr = ['a','b','c'];
var str = arr.reduce((total, item) => total + item,'s'); //sabc
使用reduce进行函数的编排
使用compose计算商品的价格:
//商品打折函数 假设0.8折
function discount(total){
return total * 0.8;
};
//商品总价 假设购买10件
function totalPrice(total){
return total * 10;
};
//运费 假设12元
function express(total){
return total + 12;
};
const compose = (fns) => (price) => fns.reduce((total, item) => item(total), price);
let p= compose([totalPrice, discount, express])(100); //812
redux的compose
再来看redux中的compose
function compose(fns){
return fns.reduce((total, item) => (...args) => total(item(args)));
}
let p = compose([totalPrice, discount, express])(100); //896.0000000000001
要注意执行顺序跟函数列表是相反的,相当于totalPrice(discount(express(100)));
koa中的compose
//koa的compose
function compose(fns) {
var result;
return function (ctx) {
var i = 0;
function dispatch(i, ctx) {
if (i === fns.length) {
result = ctx;
return;
};
var fn = fns[i];
return fn(ctx, dispatch.bind(null, ++i));
};
dispatch(0, ctx);
return result;
};
};
let p1 = compose([totalPrice, discount, express])(100); //812