compose 是一个工具函数,先看源码再分析:

  1. export default function compose(...funcs) {
  2. if (funcs.length === 0) {
  3. return arg => arg
  4. }
  5. if (funcs.length === 1) {
  6. return funcs[0]
  7. }
  8. return funcs.reduce((a, b) => (...args) => a(b(...args)))
  9. }

乍一看有点懵。😲😲😲

来熟悉下 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) 的调用方式。

最小化验证

以最小化的代码来验证这个函数:

  1. function a(dis){
  2. dis(1);
  3. return dis;
  4. }
  5. function b(dis){
  6. dis(2);
  7. return dis;
  8. }
  9. function c(dis){
  10. dis(3);
  11. return dis;
  12. }
  13. let count = 0;
  14. function dis(num){
  15. count += num;
  16. }
  17. const f = compose(...[a, b, c])(dis);
  18. console.log('count', count)

将函数dis作为参数透传,遍历执行顺序 c => b => a
最终count=6

😀😀😀