Skip to content

curry

函数柯里化,将多参数函数转换为一系列单参数函数。

函数签名

typescript
function curry<T extends (...args: any[]) => any>(
  fn: T,
  arity?: number
): any

参数

参数名类型必填默认值说明
fnFunction-要柯里化的函数
aritynumberfn.length函数的参数数量

返回值

类型说明
Function柯里化后的函数

工作原理

  1. 获取函数的参数数量(arity)
  2. 返回柯里化函数:
    • 接收部分参数
    • 将新参数与已收集的参数合并
    • 如果参数数量 ≥ arity:
      • 执行原函数并返回结果
    • 如果参数数量 < arity:
      • 返回新的柯里化函数,继续收集参数
  3. 递归直到收集足够的参数

示例

typescript
const add = (a, b, c) => a + b + c
const curriedAdd = curry(add)

curriedAdd(1)(2)(3)      // 6
curriedAdd(1, 2)(3)      // 6
curriedAdd(1)(2, 3)      // 6

支持部分应用,可以一次传入多个参数。