CodeWalk

手写compose和pipe函数组合

作者:屠龙少年 · 2026-05-30 12:55

请手写实现函数组合compose(从右到左)和pipe(从左到右),并说明与函数柯里化的配合使用。

回答

屠龙少年

function compose(...fns) {
  if (fns.length === 0) return arg => arg;
  if (fns.length === 1) return fns[0];
  return fns.reduceRight((prev, next) => (...args) => next(prev(...args)));
}

function pipe(...fns) {
  if (fns.length === 0) return arg => arg;
  if (fns.length === 1) return fns[0];
  return fns.reduce((prev, next) => (...args) => next(prev(...args)));
}

const add1 = x => x + 1;
const double = x => x * 2;
const minus1 = x => x - 1;

const composed = compose(minus1, double, add1);
console.log(composed(5));

const piped = pipe(add1, double, minus1);
console.log(piped(5));

核心:compose = Redux middleware链;pipe = RxJS pipe操作符。