compose
函数组合,从右向左执行函数序列。
函数签名
typescript
function compose<T>(...fns: Array<(arg: T) => T>): (arg: T) => T参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
...fns | Array<(arg: T) => T> | 是 | 要组合的函数序列(从右向左执行) |
返回值
| 类型 | 说明 |
|---|---|
(arg: T) => T | 组合后的函数 |
工作原理
- 返回一个新函数,接收初始参数
- 从右向左依次执行函数序列:
- 最右边的函数接收初始参数
- 每个函数的返回值作为左边函数的参数
- 最左边函数的返回值作为最终结果
- 使用
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。