js compose 实现
实现 JavaScript 的 compose 函数
compose 函数是函数式编程中的一个重要概念,它可以将多个函数组合成一个新的函数,从右到左依次执行。
基本实现
最简单的 compose 实现方式:
const compose = (...fns) =>
x => fns.reduceRight((v, f) => f(v), x);
这个实现:

- 接收任意数量的函数作为参数
- 返回一个新函数
- 使用 reduceRight 从右到左依次执行函数
- 每个函数的输出作为下一个函数的输入
使用示例
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
执行流程:
- 先执行 add5(5) 得到 10
- 然后执行 multiply2(10) 得到 20
- 最后执行 square(20) 得到 400
异步版本实现
如果需要支持异步函数组合:

const asyncCompose = (...fns) =>
x => fns.reduceRight(
(promise, fn) => promise.then(fn),
Promise.resolve(x)
);
更健壮的实现
添加参数验证和错误处理:
const compose = (...fns) => {
if (fns.some(fn => typeof fn !== 'function')) {
throw new TypeError('所有参数都必须是函数');
}
return x => fns.reduceRight((v, f) => {
try {
return f(v);
} catch (error) {
throw new Error(`函数执行错误: ${error.message}`);
}
}, x);
};
性能优化版本
使用循环代替 reduceRight 可能获得更好的性能:
const compose = (...fns) => {
const length = fns.length;
return x => {
let result = x;
for (let i = length - 1; i >= 0; i--) {
result = fns[i](result);
}
return result;
};
};
从左到右的 pipe 实现
与 compose 方向相反的 pipe 函数:
const pipe = (...fns) =>
x => fns.reduce((v, f) => f(v), x);
实际应用场景
- 中间件处理:如 Express/Koa 的中间件系统
- 数据处理流水线:对数据进行多步转换
- 函数组合:将小函数组合成更复杂的功能
这些实现方式可以根据具体需求选择使用,基本版本适用于大多数场景,特殊需求可以考虑其他变体。






