Skip to content

chunk() function

要素を size の長さのグループに分割した Iterable/AsyncIterable を返します。iterableIterator を均等に分割できない場合、最後の chunk は残りの要素になります。

Signature:

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

Example

ts
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

Released under the Apache-2.0 License.