partition
import { partition } from "jsr:@ende/collections";function
function partition<T, U extends T>(array: Iterable<T>, predicate: (el: T) => el is U): [U[], Exclude<T, U>[]]Returns a tuple of two arrays with the first one containing all elements in the given array that match the given predicate and the second one containing all that do not.
This version of the function is a type-guard version of the function. It allows you to specify a type-guard predicate function that narrows the type of the elements in the first output array.
array: Iterable<T>The array to partition.
predicate: (el: T) => el is UThe type-guard predicate function to determine which array an element belongs to.
Returns
A tuple of two arrays. The first array contains all elements that match the predicate, the second contains all elements that do not.
Example: Basic usage
import { partition } from "@ende/collections/partition";
import { assertEquals } from "@ende/assert";
const mixed = [1, "a", 2, "b"];
const isString = (x: unknown): x is string => typeof x === "string";
const [strings, others] = partition(mixed, isString);
assertEquals(strings, ["a", "b"]);
assertEquals(others, [1, 2]);
function
function partition<T>(array: Iterable<T>, predicate: (el: T, index: number) => boolean): [T[], T[]]Returns a tuple of two arrays with the first one containing all elements in the given array that match the given predicate and the second one containing all that do not.
array: Iterable<T>The array to partition.
predicate: (el: T, index: number) => booleanThe predicate function to determine which array an element belongs to. The function receives the element and its index.
Returns
A tuple of two arrays. The first array contains all elements that match the predicate, the second contains all elements that do not.
Example: Basic usage
import { partition } from "@ende/collections/partition";
import { assertEquals } from "@ende/assert";
const numbers = [5, 6, 7, 8, 9];
const [even, odd] = partition(numbers, (it) => it % 2 === 0);
assertEquals(even, [6, 8]);
assertEquals(odd, [5, 7, 9]);
Example: Using the index parameter
import { partition } from "@ende/collections/partition";
import { assertEquals } from "@ende/assert";
const array = [2, 4, 6];
const [evenIndexed, oddIndexed] = partition(
array,
(_: number, index: number) => index % 2 === 0,
);
assertEquals(evenIndexed, [2, 6]);
assertEquals(oddIndexed, [4]);
function
function partition(array: Iterable<unknown>, predicate: (el: unknown, index: number) => boolean): [unknown[], unknown[]]