Skip to main content

Function: slice()

slice<ElementType>(iterable: IterableResolvable<ElementType>, start?: number, end?: number): IterableIterator<ElementType>

Produces an iterable with the elements from the start index to the end index (exclusive).

Type Parameters

Type Parameter
ElementType

Parameters

ParameterTypeDescription
iterableIterableResolvable<ElementType>The iterator to slice.
start?numberThe index at which to begin extraction.
end?numberThe index at which to end extraction.

Returns

IterableIterator<ElementType>

An iterator that contains the elements of the provided iterator from start to end.

Examples

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

const iterable = [1, 2, 3, 4, 5];
console.log([...slice(, 1, 3)]);
// Output: [2, 3]
const iterable = [1, 2, 3, 4, 5];
console.log([...slice(iterable, -2)]);
// Output: [4, 5]
const iterable = [1, 2, 3, 4, 5];
console.log([...slice(iterable, 2)]);
// Output: [3, 4, 5]
const iterable = [1, 2, 3, 4, 5];
console.log([...slice(iterable, 2, -1)]);
// Output: [3, 4]
const iterable = [1, 2, 3, 4, 5];
console.log([...slice(iterable, -2, -1)]);
// Output: [4]
const iterable = [1, 2, 3, 4, 5];
console.log([...slice(iterable, 2, 1)]);
// Output: []

Remarks

This function consumes the input iterator based on the start and end values, therefore, you should not use the original iterator after calling this function.

Defined in

projects/utilities/packages/iterator-utilities/src/lib/slice.ts:66