Skip to content

compose

函数组合,从右向左执行函数序列。

函数签名

typescript
function compose<T>(...fns: Array<(arg: T) => T>): (arg: T) => T

参数

参数名类型必填说明
...fnsArray<(arg: T) => T>要组合的函数序列(从右向左执行)

返回值

类型说明
(arg: T) => T组合后的函数

工作原理

  1. 返回一个新函数,接收初始参数
  2. 从右向左依次执行函数序列:
    • 最右边的函数接收初始参数
    • 每个函数的返回值作为左边函数的参数
    • 最左边函数的返回值作为最终结果
  3. 使用 reduceRight 实现:fns.reduceRight((acc, fn) => fn(acc), initialValue)

示例

typescript
const add1 = (x) => x + 1
const double = (x) => x * 2
const square = (x) => x * x

const composed = compose(square, double, add1)
composed(3) // square(double(add1(3))) = square(double(4)) = square(8) = 64

执行顺序:右→左(add1 → double → square),符合数学中的函数组合 f∘g∘h