# 函数式编程 compose
实现以下功能:
compose([a, b, c])('参数')
=>
a( b( c('参数') ) )
1
2
3
2
3
function compose(funcs) {
var len = funcs.length;
var index = len - 1;
for(let i = 0; i < len; i ++) {
if(typeof funcs[i] !== 'function') {
throw new TypeError('Expected function');
}
}
return function (...args) {
let result = funcs[index](...args) // 第一次
while(--index >= 0) {
result = funcs[index](result)
}
return result;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
测试:
function a (str) {
return `a ${str}`
}
function b (str) {
return `b ${str}`
}
function c (str) {
return `c ${str}`
}
const abc = compose([a, b, c])
abc('huyao')
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12