Skip to main content

Function: partition()

partition(iterable, predicate)

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

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.

Source

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

partition(iterable, predicate)

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

Type parameters

Type parameter
ElementType

Parameters

ParameterType
iterableIterableResolvable<ElementType>
predicate(value: ElementType, index: number) => boolean

Returns

[ElementType[], ElementType[]]

Source

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