Partition by predicate in TypeScript
Splits an array in two by a predicate, narrowing the type when the predicate is a guard.
function partition<T>(
items: T[],
predicate: (item: T) => boolean,
): [T[], T[]] {
const pass: T[] = [];
const fail: T[] = [];
for (const item of items) {
(predicate(item) ? pass : fail).push(item);
}
return [pass, fail];
}
Keywords and builtins used here
Tbooleanconstfailforfunctionofreturn
The run, in numbers
- Lines
- 11
- Characters to type
- 224
- Tokens
- 87
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 50 seconds.
Step 5 of 11 in Generic helpers, step 13 of 20 in Generics.