compose javascript

在阅读某段代码的时候,了解到了compose 但是似乎不止redux 很多工具库都用到了这个function

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 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))).
*/

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)))
}

以前的写法:

1
fn1(fn2(fn3(fn4(fnN(...)))))

现在的写法:

1
compose(fn1, fn2, fn3, fn4, fnN)(...)

相关链接:

redux

Use function composition in JavaScript

redux之compose

redux compose 详解

打赏测试