Skip to main content

chunk

chunk() function

Returns Iterable/AsyncIterable of elements split into groups the length of size. If iterableIterator can't be split evenly, the final chunk will be the remaining elements.

Signature:
declare function chunk<T>(size: number, iterable: Iterable<T>): IterableIterator<T[]>;

declare function chunk<T>(size: number, iterable: AsyncIterable<T>): AsyncIterableIterator<T[]>;

declare function chunk<T extends Iterable<unknown> | AsyncIterable<unknown>>(size: number): (iterable: T) => ReturnIterableIteratorType<T, IterableInfer<T>[]>;

Example

const iter = chunk(2, [1, 2, 3, 4]);
iter.next() // {done:false, value:[1, 2]}
iter.next() // {done:false, value:[3, 4]}
iter.next() // {done:true, value: undefined}

// with pipe
pipe(
[1, 2, 3, 4],
chunk(2),
toArray,
); // [[1, 2],[3, 4]]

await pipe(
Promise.resolve([1, 2, 3 ,4]),
chunk(2),
toArray,
); // [[1, 2],[3, 4]]

// with toAsync
await pipe(
[Promise.resolve(1), Promise.resolve(2), Promise.resolve(3), Promise.resolve(4)],
toAsync,
chunk(2),
toArray,
); // [[1, 2],[3, 4]]

Try It

see pipe, toAsync, toArray

Open Source Code