let fn1 = function (x) {
return x + 10;
};
let fn2 = function (x) {
return x * 10;
};
let fn3 = function (x) {
return x / 10;
};
console.log(fn3(fn1(fn2(fn1(5))))); //=> ((5+10)*10+10)/10 => 16
编写compose函数实现调用扁平化
function compose(...funcs) {
//=>funcs:传递的函数集合
return function proxy(...args) {
//=>args:第一次调用函数传递的参数集合
let len = funcs.length;
if (len === 0) {
//=>一个函数都不需要执行,直接返回ARGS
return args;
}
if (len === 1) {
//=>只需要执行一个函数,把函数执行,把其结果返回即可
return funcs[0](...args);
}
return funcs.reduce((x, y) => {
return typeof x === "function" ? y(x(...args)) : y(x);
});
};
}
//=>compose函数调用的扁平化
console.log(compose()(5)); //=>5
console.log(compose(fn1)(5)); //=>5+10 = 15
console.log(compose(fn1, fn2)(5)); //=>fn1(5)=15 fn2(15)=150 ...
console.log(compose(fn1, fn2, fn1, fn3)(5)); //=>16
compose函数实现函数调用扁平化
最新推荐文章于 2023-06-09 10:40:48 发布