# 一. 基础
compose是函数式编程中一个非常重要的函数,compose的函数作用就是组合函数的,将函数串联起来执行。将多个函数组合起来,一个函数的输出记过是另一个函数的输入参数,一旦第一个函数开始执行,就会像多米诺骨牌一样推导执行。
简而言之:compose 可以把类似于f(g(h(x)))这种写法简化成 compose(f, g, h)(x)
例1:可读性差
const add1 = (x) => x + 1;
const mul3 = (x) => x * 3;
const div2 = (x) => x / 2;
div2(mul3(add1(add1(0)))); //=>3
例2:
const operate = compose(div2, mul3, add1, add1)
operate(0) //=>相当于div2(mul3(add1(add1(0))))
operate(2) //=>相当于div2(mul3(add1(add1(2))))
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 二. 实现
let compose = function (...funcs) {
var length = funcs.length;
var index = length;
while (index--) {
//确保每个参数都是函数
if (typeof funcs[index] !== "function") {
throw new TypeError("Expected a function");
}
}
return function (...args) {
var index = length - 1;
var result = length ? funcs[index].apply(this, args) : args[0];
while (--index >= 0) {
result = funcs[index].call(this, result);
}
return result;
};
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18