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']
注意事項
- 保持原數組不變:
fork
不會修改原數組,而是返回新的數組 - 條件函數: 條件函數應該返回布爾值,決定元素屬於哪個數組
- 空數組處理: 如果原數組為空,返回兩個空數組
- 性能: 時間復雜度為 O(n),其中 n 是數組長度
與其他方法的區別
filter()
: 只返回滿足條件的元素fork()
: 返回兩個數組,分別包含滿足和不滿足條件的元素partition()
: 類似功能,但fork
更簡潔
實際應用場景
- 用戶管理: 分離活躍和非活躍用戶
- 數據處理: 分離有效和無效數據
- 文件處理: 分離成功和失敗的文件操作
- 表單驗證: 分離通過和未通過驗證的字段