VDL Plugin SDK

partition

Import from @varavel/vdl-plugin-sdk/utils/arrays.

Utility functions re-exported from es-toolkit (MIT License). See https://github.com/toss/es-toolkit for more details.

Call Signature

function partition<T, U>(arr, isInTruthy): [truthy: U[], falsy: Exclude<T, U>[]];

Splits an array into two groups based on a predicate function.

This function takes an array and a predicate function. It returns a tuple of two arrays: the first array contains elements for which the predicate function returns true, and the second array contains elements for which the predicate function returns false.

Type Parameters

Type ParameterDescription
TThe type of elements in the array.
UThe type being filtered for.

Parameters

ParameterTypeDescription
arrreadonly T[]The array to partition.
isInTruthy(value, index, array) => value is UA type guard that determines whether an element should be placed in the truthy array. The function is called with each element of the array and its index.

Returns

[truthy: U[], falsy: Exclude<T, U>[]]

A tuple containing two arrays: the first array contains elements for which the predicate returned true, and the second array contains elements for which the predicate returned false.

Example

const array = [1, 2, 3, 4] as const;
const isEven = (x: number): x is 2 | 4 => x % 2 === 0;
const [even, odd]: [(2 | 4)[], (2 | 4)[]] = partition(array, isEven);
// even will be [2, 4], and odd will be [1, 3]

Call Signature

function partition<T>(arr, isInTruthy): [truthy: T[], falsy: T[]];

Splits an array into two groups based on a predicate function.

This function takes an array and a predicate function. It returns a tuple of two arrays: the first array contains elements for which the predicate function returns true, and the second array contains elements for which the predicate function returns false.

Type Parameters

Type ParameterDescription
TThe type of elements in the array.

Parameters

ParameterTypeDescription
arrreadonly T[]The array to partition.
isInTruthy(value, index, array) => unknownA predicate function that determines whether an element should be placed in the truthy array. An element is placed in the truthy array when the function returns a truthy value. The function is called with each element of the array and its index.

Returns

[truthy: T[], falsy: T[]]

A tuple containing two arrays: the first array contains elements for which the predicate returned a truthy value, and the second array contains elements for which the predicate returned a falsy value.

Example

const array = [1, 2, 3, 4, 5];
const isEven = x => x % 2 === 0;
const [even, odd] = partition(array, isEven);
// even will be [2, 4], and odd will be [1, 3, 5]