js实现compose
实现compose函数的方法
在JavaScript中,compose函数用于将多个函数组合成一个新函数,新函数的执行顺序是从右到左。以下是几种实现方式:
基础实现
const compose = (...fns) =>
x => fns.reduceRight((acc, fn) => fn(acc), x);
支持异步函数的实现
const compose = (...fns) =>
async x => fns.reduceRight(async (acc, fn) => fn(await acc), x);
使用递归的实现
const compose = (...fns) => {
const [first, ...rest] = fns.reverse();
return (...args) => rest.reduce((acc, fn) => fn(acc), first(...args));
};
使用示例
const add5 = x => x + 5;
const multiply2 = x => x * 2;
const square = x => x * x;
const composedFn = compose(square, multiply2, add5);
console.log(composedFn(5)); // 输出: 400 (5+5=10, 10*2=20, 20*20=400)
注意事项
- 确保传入的参数都是函数类型
- 空参数列表会返回一个恒等函数
- 考虑错误处理机制
- 性能考虑:大量函数组合可能影响性能
变体实现
从左到右执行的pipe函数
const pipe = (...fns) =>
x => fns.reduce((acc, fn) => fn(acc), x);
支持初始多参数的实现

const compose = (...fns) =>
(...args) => fns.reduceRight((acc, fn) => fn(acc), fns.pop()(...args));






