compose函数
compose是函数式编程中使用较多的一种写法, 它把逻辑解耦在各个函数中,通过compose的方式组合函数, 将外部数据依次通过各个函数的加工,生成结果。
在函数式编程当中有一个很重要的概念就是函数组合, 实际上就是把处理数据的函数像管道一样连接起来, 然后让数据穿过管道得到最终的结果。
// 例1:
const add1 = (x) => x + 1;
const add1 = (x) => x + 1;
const mul3 = (x) => x * 3;
const div2 = (x) => x / 2;
div2(mul3(add1(add1(0)))); //=>3
而这样的写法可读性明显太差了,我们可以构建一个compose函数,它接受任意多个函数作为参数(这些函数都只接受一个参数),然后compose返回的也是一个函数,达到以下的效果:
const operate = compose(div2, mul3, add1, add1)
//执行方式是从右到左,只有一个同一参数
operate(0) //=>相当于div2(mul3(add1(add1(0))))
operate(2) //=>相当于div2(mul3(add1(add1(2))))
// 开始构建compose方法
const compose = function(){// arguments 参数集
// 将接收的参数存到一个数组, args == [div2, mul3, add1, add]
const args = [].slice.apply(arguments);
return function(x) {
return args.reduceRight(function(res, cb) {
return cb(res);
}, x);
}
}
// es6写法
const compose = (...args) => x => args.reduceRight((res,cb) => cb(res), x);
pipe函数
pipe函数是和compose函数是一样的,只是执行参数方法的时候是由左向右执行的。
// 开始构建pipe方法
const pipe = function(){// arguments 参数集
// 将接收的参数存到一个数组, args == [div2, mul3, add1, add]
// reverse() 方法用于颠倒数组中元素的顺序。如果使用这个方法颠倒参数,后续仍可使用reduceRight()
const args = [].slice.apply(arguments);
return function(x) {
return args.reduce(function(res, cb) {
return cb(res);
}, x);
}
}
// es6写法
const pipe = (...args) => x => args.reduce((res,cb) => cb(res), x);