compose
是一个工具函数,先看源码再分析:
export default 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)))
}
乍一看有点懵。😲😲😲
来熟悉下 reduce
的用法:arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
参数:callback
回调函数accumulator
累计器累积回调的返回值,它是上一次调用的回调时返回的累积值 或 initialValue
;currentValue
数组中当前值;index
可选,数组中当前的索引;array
可选,调用reduce的数组;initialValue
可选,作为第一次调用callback
时的初始值;
好,回到我们的源码中来:funcs.reduce((a, b) => (...args) => a(b(...args)))
因为有两个返回函数,所以 compose
的返回值是个函数。调用这个函数,会将这个函数的参数透传下去。
简单理解:
就是将 const f = f1(f2(f3(f4(dispatch))))
变成 const f = componse(f1,f2,f3,f4)(dispatch)
的调用方式。
最小化验证
以最小化的代码来验证这个函数:
function a(dis){
dis(1);
return dis;
}
function b(dis){
dis(2);
return dis;
}
function c(dis){
dis(3);
return dis;
}
let count = 0;
function dis(num){
count += num;
}
const f = compose(...[a, b, c])(dis);
console.log('count', count)
将函数dis
作为参数透传,遍历执行顺序 c
=> b
=> a
。
最终count=6
。
😀😀😀