Skip to content

fork

将数组分成两个数组,一个包含满足条件的元素,另一个包含不满足条件的元素。

基础用法

typescript
import { fork } from 'radash'

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

const [evens, odds] = fork(numbers, x => x % 2 === 0)
// evens: [2, 4, 6, 8, 10]
// odds: [1, 3, 5, 7, 9]

语法

typescript
function fork<T>(
  array: readonly T[],
  condition: (item: T, index: number, array: readonly T[]) => boolean
): [T[], T[]]

参数

  • array (readonly T[]): 要分叉的数组
  • condition (function): 用于判断元素是否满足条件的函数
    • item (T): 当前元素
    • index (number): 当前元素的索引
    • array (readonly T[]): 原数组

返回值

返回一个包含两个数组的元组:

  • 第一个数组:满足条件的元素
  • 第二个数组:不满足条件的元素

示例

分离用户

typescript
import { fork } from 'radash'

const users = [
  { id: 1, name: 'Alice', age: 25, active: true },
  { id: 2, name: 'Bob', age: 30, active: false },
  { id: 3, name: 'Charlie', age: 35, active: true },
  { id: 4, name: 'Diana', age: 28, active: false }
]

const [activeUsers, inactiveUsers] = fork(users, user => user.active)

console.log(activeUsers)
// [
//   { id: 1, name: 'Alice', age: 25, active: true },
//   { id: 3, name: 'Charlie', age: 35, active: true }
// ]

console.log(inactiveUsers)
// [
//   { id: 2, name: 'Bob', age: 30, active: false },
//   { id: 4, name: 'Diana', age: 28, active: false }
// ]

分离数字

typescript
import { fork } from 'radash'

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// 分离正数和负数
const [positives, negatives] = fork(numbers, x => x > 0)
// positives: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// negatives: []

// 分离大于5和小于等于5的数字
const [large, small] = fork(numbers, x => x > 5)
// large: [6, 7, 8, 9, 10]
// small: [1, 2, 3, 4, 5]

分离字符串

typescript
import { fork } from 'radash'

const words = ['apple', 'banana', 'cherry', 'date', 'elderberry']

const [longWords, shortWords] = fork(words, word => word.length > 5)
// longWords: ['banana', 'cherry', 'elderberry']
// shortWords: ['apple', 'date']

使用索引

typescript
import { fork } from 'radash'

const items = ['a', 'b', 'c', 'd', 'e']

const [firstHalf, secondHalf] = fork(items, (_, index) => index < 2)
// firstHalf: ['a', 'b']
// secondHalf: ['c', 'd', 'e']

注意事项

  1. 保持原数组不变: fork 不会修改原数组,而是返回新的数组
  2. 条件函数: 条件函数应该返回布尔值,决定元素属于哪个数组
  3. 空数组处理: 如果原数组为空,返回两个空数组
  4. 性能: 时间复杂度为 O(n),其中 n 是数组长度

与其他方法的区别

  • filter(): 只返回满足条件的元素
  • fork(): 返回两个数组,分别包含满足和不满足条件的元素
  • partition(): 类似功能,但 fork 更简洁

实际应用场景

  1. 用户管理: 分离活跃和非活跃用户
  2. 数据处理: 分离有效和无效数据
  3. 文件处理: 分离成功和失败的文件操作
  4. 表单验证: 分离通过和未通过验证的字段

Released under the MIT License.