1. 目的
实现函数compose,使得let composeFn = compose(fn, gn, ln),
执行composeFn(x)输出fn( gn( ln(x) ) )的执行结果
2. 通用代码
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;
};
};
- 有点类似于
Promise将我们从callback嵌套地狱中解救一样 - 完全可以使用lodash的
flowRight
3. 使用场景
- 函数式编程,高阶函数的组合式调用