js compose 实现
实现 JavaScript 的 compose 函数
compose 是一种函数式编程概念,用于将多个函数组合成一个函数,从右到左依次执行。以下是几种实现方式:
基础实现
const compose = (...fns) =>
(x) => fns.reduceRight((acc, fn) => fn(acc), x);
使用示例:
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)); // ((5 + 5) * 2)^2 = 400
支持异步函数的实现
const asyncCompose = (...fns) =>
(x) => fns.reduceRight(
(acc, fn) => Promise.resolve(acc).then(fn),
Promise.resolve(x)
);
从左到右的管道(pipeline)实现
const pipe = (...fns) =>
(x) => fns.reduce((acc, fn) => fn(acc), x);
使用递归的实现
const recursiveCompose = (...fns) => {
const [first, ...rest] = fns.reverse();
return (...args) => rest.reduce(
(acc, fn) => fn(acc),
first(...args)
);
};
实现原理说明
compose 函数利用了数组的 reduceRight 方法,从右到左依次执行函数:
- 初始值是传入的参数
x - 每个函数将前一个函数的返回值作为输入
- 最终返回组合后的函数
性能考虑
对于大量函数的组合,可能需要考虑性能优化:
- 避免在循环或高频调用的地方使用
compose - 对于固定组合,可以预先计算并缓存组合结果
类型安全的 TypeScript 实现
type Func<T, R> = (arg: T) => R;
function compose<T1, T2, T3>(
fn1: Func<T2, T3>,
fn2: Func<T1, T2>
): Func<T1, T3>;
function compose<T1, T2, T3, T4>(
fn1: Func<T3, T4>,
fn2: Func<T2, T3>,
fn3: Func<T1, T2>
): Func<T1, T4>;
// 可以继续添加更多重载
function compose(...fns: Function[]) {
return (x: any) => fns.reduceRight((acc, fn) => fn(acc), x);
}
应用场景
compose 适用于:

- 数据处理流水线
- 中间件系统
- 函数转换链
- 避免深层嵌套函数调用






