Skip to main content

Function: partition()

Call Signature​

partition<ElementType, FilteredType>(iterable: IterableResolvable<ElementType>, predicate: (value: ElementType, index: number) => value is FilteredType): [FilteredType[], Exclude<ElementType, FilteredType>[]]

Defined in: projects/utilities/packages/iterator-utilities/src/lib/partition.ts:32

Consumes the iterable and creates two arrays, one with the elements that pass the test and another with the elements that don't.

Type Parameters​

Type Parameter
ElementType
FilteredType

Parameters​

ParameterTypeDescription
iterableIterableResolvable<ElementType>An iterator to partition.
predicate(value: ElementType, index: number) => value is FilteredTypeA function that determines which partition an element belongs to.

Returns​

[FilteredType[], Exclude<ElementType, FilteredType>[]]

An array containing two iterators. The first iterator contains elements that satisfy the predicate, and the second iterator contains elements that do not.

Example​

import { partition } from '@sapphire/iterator-utilities';

const iterable = [1, 2, 3, 4, 5];
const [even, odd] = partition(iterable, (value) => value % 2 === 0);

console.log(even);
// Output: [2, 4]

console.log(odd);
// Output: [1, 3, 5]

Remarks​

This function collects all elements of the provided iterator into two arrays based on the predicate before returning them, which may not be desirable for large iterators.

Call Signature​

partition<ElementType>(iterable: IterableResolvable<ElementType>, predicate: (value: ElementType, index: number) => boolean): [ElementType[], ElementType[]]

Defined in: projects/utilities/packages/iterator-utilities/src/lib/partition.ts:36

Consumes the iterable and creates two arrays, one with the elements that pass the test and another with the elements that don't.

Type Parameters​

Type Parameter
ElementType

Parameters​

ParameterTypeDescription
iterableIterableResolvable<ElementType>An iterator to partition.
predicate(value: ElementType, index: number) => booleanA function that determines which partition an element belongs to.

Returns​

[ElementType[], ElementType[]]

An array containing two iterators. The first iterator contains elements that satisfy the predicate, and the second iterator contains elements that do not.

Example​

import { partition } from '@sapphire/iterator-utilities';

const iterable = [1, 2, 3, 4, 5];
const [even, odd] = partition(iterable, (value) => value % 2 === 0);

console.log(even);
// Output: [2, 4]

console.log(odd);
// Output: [1, 3, 5]

Remarks​

This function collects all elements of the provided iterator into two arrays based on the predicate before returning them, which may not be desirable for large iterators.