-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
94 lines (88 loc) · 2.4 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import type {
AssignableTo,
ToMutableArray,
inferReversePredicate,
} from '../../types'
/**
* Creates two arrays, the first containing the elements for which
* the predicate returned true, and the second containing the elements
* for which the predicate returned false.
*
* @param array The array to partition.
* @param predicate The predicate to match the elements against.
* @returns A tuple containing the two arrays.
*
* @example
* #### Basic usage
* ```ts
* const [even, odd] = partition(
* [1, 2, 3, 4, 5],
* (n) => n % 2 === 0 // (true if n is even)
* )
* console.log(even) // [2, 4]
* console.log(odd) // [1, 3, 5]
* ```
*
* #### Type narrowing
* ```ts
* import { isString } from 'uft'
*
* const [strings, other] = partition(
* [1, 'foo', { bar: '' }],
* isString
* )
* strings // type: string[]
* other // type: (number | { bar: string })[]
* ```
* @category Array
*/
// Requires that the type predicate of `predicate` extends
// one of the elements of the array.
export function partition<
T extends readonly unknown[],
S extends T[number],
>(
array: T,
predicate: (element: T[number], index: number) => element is S
): [
trueElements: S[],
falseElements: inferReversePredicate<typeof predicate>[],
]
// Requires that an element of the array extends the
// type predicate of `predicate`. See `filteredForEach`
// for more information.
export function partition<
T extends readonly unknown[],
S,
>(
array: T,
predicate: (element: T[number], index: number) => element is S
): [
trueElements: AssignableTo<T[number], S>[],
falseElements: AssignableTo<
T[number],
inferReversePredicate<typeof predicate>
>[],
]
// Does not require the use of a type predicate.
export function partition<T extends readonly unknown[]>(
array: T,
predicate: (element: T[number], index: number) => boolean
): [
trueElements: ToMutableArray<T>,
falseElements: ToMutableArray<T>,
]
export function partition(
array: unknown[],
predicate: (element: unknown, index: number) => boolean
): [trueElements: unknown[], falseElements: unknown[]] {
const trueElements: unknown[] = []
const falseElements: unknown[] = []
for (let idx = 0; idx < array.length; idx++) {
const element = array[idx]!
predicate(element, idx)
? trueElements.push(element)
: falseElements.push(element)
}
return [trueElements, falseElements]
}