Redux源码解析03--compose

compose

composeapplyMiddleware的helper函数,用于将多个middleware组成逐级嵌套,使用next进行控制权移交的形式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 将多个function从左到右互相嵌套起来,只有最右边的函数能接收多个参数,其他的都是单参数
* 例如:compose(f, g, h) 等同于 (...args) => f(g(h(...args)))
* @param funcs
* @return {*}
*/
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)))
}