学习reduce()时遇到一个练习“功能型函数管道”,对于代码中的pipe不能理解,类似于下面这一行代码,信息量很丰富,有es6中的扩展运算符,箭头函数,reduce()方法。
const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
展开:
const pipe = function(x, ...fns) {
fns.reduce((y, f) => f(y), x);
}
进一步拆解:
function pipe(x, ...fns){
let accu= x;
for(let f in fns){
accu= f(accu)
}
return accu;
}
这样就容易看清。
对于pipe()函数,当我们调用pipe(x, f1, f2)时,返回f2(f1(x))