partition

Divide un array en dos basándose en una función predicado.

#array #utility #filtering
export const partition = <T>(
arr: readonly T[],
predicate: (item: T) => boolean,
): [T[], T[]] => {
const truthy: T[] = [];
const falsy: T[] = [];
for (const item of arr) {
(predicate(item) ? truthy : falsy).push(item);
}
return [truthy, falsy];
};
// Usage
const [evens, odds] = partition([1, 2, 3, 4, 5], n => n % 2 === 0);
// evens: [2, 4]
// odds: [1, 3, 5]

Comparte este snippet

Comentarios