Redux compose()方法解析:

368 阅读1分钟

compose()主要是利用了数组的reduce()方法来实现迭代:第二个函数的执行结果,作为第一个函数的参数。

/**此处是源代码
 * Composes single-argument functions from right to left. The rightmost
 * function can take multiple arguments as it provides the signature for
 * the resulting composite function.
 *
 * @param {...Function} funcs The functions to compose.
 * @returns {Function} A function obtained by composing the argument functions
 * from right to left. For example, compose(f, g, h) is identical to doing
 * (...args) => f(g(h(...args))).
 */
 function compose(...funcs) {
    if (funcs.length === 0) {
        return arg => arg
    }
    if (funcs.length === 1) {
        return funcs[0]
    }
    return funcs.reduce((a, b) => (...args) => a(b(...args)))
}

分析如下:

function compose(...funcs) {
    //reduce 数组元素的迭代,每次迭代都返回一个函数
    //第二个函数的执行结果,作为第一个函数的参数
    return funcs.reduce((a, b) => (...args) => a(b(...args)))
}
function f1(a){
    return a+1;
}
function f2(a){
    return a*10;
}
function f3(a){
    return a-1;
}

var compo=compose(f1,f2,f3);
console.log(compo);//Function
console.log(compo(3));//21

compose(f1,f2,f3)

//第一次迭代后的返回值
(...args) => f1(f2(...args))  等价于
function fn(...args) {
    return f1(f2(...args));
}
//第二次迭代后的返回值
// return (...args) => fn(f3(...args))   等价于
// return (...args) => f1(f2(f3(...args)));    等价于
// function fn(f3(...args)) {
//     return f1(f2(f3(...args)));
// }

备注: 函数数组里面,最后一个函数可以有多个参数,其它函数只能有一个参数。