All files / collections / unstable_chunk.ts

100.00% Branches 12/12
100.00% Lines 29/29
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x2
x2
x2
 
x39
x44
x44
 
x44
x71
 
 
x39
x53
x53
x80
x80
x80
x53
x53
 
x93
x75
x174
x174
x219
x219
x219
x174
x75
x78
x78
x93
x39









































































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

/**
 * Splits the given array into an array of chunks of the given size and returns them.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @typeParam T The type of the elements in the iterable.
 *
 * @param iterable The iterable to take elements from.
 * @param size The size of the chunks. This must be a positive integer.
 *
 * @returns An array of chunks of the given size.
 *
 * @example Basic usage
 * ```ts
 * import { chunk } from "@std/collections/unstable-chunk";
 * import { assertEquals } from "@std/assert";
 *
 * const words = [
 *   "lorem",
 *   "ipsum",
 *   "dolor",
 *   "sit",
 *   "amet",
 *   "consetetur",
 *   "sadipscing",
 * ];
 * const chunks = chunk(words, 3);
 *
 * assertEquals(
 *   chunks,
 *   [
 *     ["lorem", "ipsum", "dolor"],
 *     ["sit", "amet", "consetetur"],
 *     ["sadipscing"],
 *   ],
 * );
 * ```
 */
export function chunk<T>(
  iterable: Iterable<T>,
  size: number,
): T[][] {
  if (size <= 0 || !Number.isInteger(size)) {
    throw new RangeError(
      `Expected size to be an integer greater than 0 but found ${size}`,
    );
  }
  const result: T[][] = [];

  // Faster path
  if (Array.isArray(iterable)) {
    let index = 0;
    while (index < iterable.length) {
      result.push(iterable.slice(index, index + size));
      index += size;
    }
    return result;
  }

  let chunk: T[] = [];
  for (const item of iterable) {
    chunk.push(item);
    if (chunk.length === size) {
      result.push(chunk);
      chunk = [];
    }
  }
  if (chunk.length > 0) {
    result.push(chunk);
  }
  return result;
}