@monstermann/fn
Version:
A utility library for TypeScript.
32 lines (30 loc) • 817 B
JavaScript
import { dfdlT } from "@monstermann/dfdl";
//#region src/array/partition.ts
/**
* `partition(array, predicate)`
*
* Splits `array` into two arrays based on the `predicate` function, returning a tuple where the first array contains elements that satisfy the predicate and the second contains those that don't.
*
* ```ts
* partition([1, 2, 3, 4, 5], (x) => x % 2 === 0); // [[2, 4], [1, 3, 5]]
* ```
*
* ```ts
* pipe(
* [1, 2, 3, 4, 5],
* partition((x) => x % 2 === 0),
* ); // [[2, 4], [1, 3, 5]]
* ```
*/
const partition = dfdlT((target, predicate) => {
const left = [];
const right = [];
for (let i = 0; i < target.length; i++) {
const value = target[i];
if (predicate(value, i, target)) left.push(value);
else right.push(value);
}
return [left, right];
}, 2);
//#endregion
export { partition };