Skip to content

cond

条件执行函数,根据条件列表选择执行对应的函数。

函数签名

typescript
function cond<T, R>(
  conditions: Array<[predicate: (value: T) => boolean, transform: (value: T) => R]>
): (value: T) => R | undefined

参数

参数名类型必填说明
conditionsArray<[predicate, transform]>条件-函数对数组

返回值

类型说明
(value: T) => R | undefined条件执行函数,返回第一个满足条件的函数的结果,都不满足返回 undefined

工作原理

  1. 返回条件执行函数
  2. 执行时遍历条件数组:
    • 对每个条件对 [predicate, transform]
      • 执行 predicate(value) 检查条件
      • 如果返回 true:
        • 执行 transform(value)
        • 返回结果并停止遍历
  3. 如果所有条件都不满足,返回 undefined

示例

typescript
const getGrade = cond([
  [(score) => score >= 90, () => 'A'],
  [(score) => score >= 80, () => 'B'],
  [(score) => score >= 70, () => 'C'],
  [(score) => score >= 60, () => 'D'],
  [() => true, () => 'F']
])

getGrade(85)  // 'B'

类似 if-else 链或 switch 语句,但以函数式风格实现,更易于组合和测试。