const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
复制代码
一行代码中信息量是很是丰富的,能够从如下几个方面来分析数组
...
是ES6标准中的数组扩展运算符bash
扩展运算符能够展开数组: Math.max(...[1,2,3])
等价于 Math.max(1,2,3)
函数
同时与解构赋值结合起来,用于生成数组,上述代码示例中就是使用该方法,具体例子: [...fns] = [1,2,3]
则fns=[1,2,3]
ui
let [a,b,c] = [1,2,3]
柯里化函数是一种由须要接受多个参数的函数转化为一次只接受一个参数的函数:若是一个函数须要3个参数,那柯里化后的函数会接受一个参数并返回一个函数来接受下一个函数,这个函数返回的函数去传入第三个参数,最后一个函数会应用了全部参数的函数结果。this
将上述代码示例转换一下形式:spa
const pipe = function(x, ...fns) {
fns.reduce((y, f) => f(y), x);
}
复制代码
为了看到pipe函数的实际做用,进一步将上述函数进行拆解,用最简单的语法表示,以更清楚窥探其内部原理prototype
function pipe(x, ...fns){
let total = x;
for(let f in fns){
total = f(total)
}
return total;
}
复制代码
当咱们调用pipe(x, f1, f2)
时,返回f2(f1(x))rest
代码示例code
const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
const f1 = x => {
return x+1;
}
const f2 = x => {
return 2 * x;
}
// (1+1)*2 = 4
let result = pipe(f1, f2)(1);
console.log(result);
复制代码