js compose 实现
实现 JavaScript 的 compose 函数
compose 函数是函数式编程中的核心概念,用于将多个函数组合成一个函数,从右到左依次执行。以下是几种实现方式:

基础实现(ES5)
function compose() {
var fns = Array.prototype.slice.call(arguments);
return function (x) {
return fns.reduceRight(function (acc, fn) {
return fn(acc);
}, x);
};
}
ES6 简化版
const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);
支持异步函数的实现
const asyncCompose = (...fns) => async x => {
let result = x;
for (let i = fns.length - 1; i >= 0; i--) {
result = await fns[i](result);
}
return result;
};
使用示例
const add5 = x => x + 5;
const multiply2 = x => x * 2;
const square = x => x * x;
const composedFn = compose(square, multiply2, add5);
console.log(composedFn(3)); // 输出: 256 (3+5=8, 8*2=16, 16*16=256)
实现要点
- 参数收集:使用 rest 参数
...fns收集所有传入的函数 - 执行顺序:通过
reduceRight确保从右到左执行 - 初始值:将输入值
x作为初始值传递给第一个执行的函数
扩展实现(从左到右的 pipe)
const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x);






