js实现compose
实现 compose 函数的方法
在 JavaScript 中,compose 函数用于将多个函数组合成一个新的函数,新函数的执行顺序是从右到左。以下是几种实现 compose 的方法:
使用 reduce 实现
const compose = (...fns) =>
fns.reduce((f, g) => (...args) => f(g(...args)));
递归实现
const compose = (...fns) => {
const [first, ...rest] = fns.reverse();
return (...args) => rest.reduce((res, fn) => fn(res), first(...args));
};
使用 reduceRight 实现
const compose = (...fns) =>
fns.reduceRight((prevFn, nextFn) =>
(...args) => nextFn(prevFn(...args))
);
示例用法
const add5 = x => x + 5;
const multiply2 = x => x * 2;
const subtract3 = x => x - 3;
const composedFn = compose(subtract3, multiply2, add5);
console.log(composedFn(5)); // 输出: (5 + 5) * 2 - 3 = 17
实现 pipe 函数的方法
pipe 函数与 compose 类似,但执行顺序是从左到右。以下是实现方式:

使用 reduce 实现
const pipe = (...fns) =>
fns.reduce((f, g) => (...args) => g(f(...args)));
示例用法
const pipedFn = pipe(add5, multiply2, subtract3);
console.log(pipedFn(5)); // 输出: ((5 + 5) * 2) - 3 = 17
注意事项
compose和pipe的区别在于函数的执行顺序。- 确保传入的函数参数是可执行的,否则会抛出错误。
- 可以结合箭头函数和剩余参数(
...)简化实现。






