|
1
|
/** |
|
2
|
* Partitions an array into two arrays based on a predicate function |
|
3
|
|
|
4
|
* @example |
|
5
|
* const result = partitionArray([1, 2, 3, 4, 5], (x) => x % 2 === 0) |
|
6
|
* |
|
7
|
* console.log(result) |
|
8
|
* |
|
9
|
* // output: [[2, 4], [1, 3, 5]] |
|
10
|
* |
|
11
|
* @param {T} input input array of type T |
|
12
|
* @param {(T) => boolean} predicate function to use when split array elements |
|
13
|
*/ |
|
14
|
export const partitionArray = <T>( |
|
15
|
input: T[], |
|
16
|
predicate: (T) => boolean |
|
17
|
): [T[], T[]] => { |
|
18
|
return input.reduce( |
|
19
|
([pos, neg], currentElement) => { |
|
20
|
if (predicate(currentElement)) { |
|
21
|
pos.push(currentElement) |
|
22
|
} else { |
|
23
|
neg.push(currentElement) |
|
24
|
} |
|
25
|
|
|
26
|
return [pos, neg] |
|
27
|
}, |
|
28
|
[[], []] as [T[], T[]] |
|
29
|
) |
|
30
|
} |