/
chunk.ts
46 lines (40 loc) · 1.19 KB
/
chunk.ts
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
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
/**
* Splits the given array into chunks of the given size and returns them
*
* Example:
*
* ```ts
* import { chunk } from "https://deno.land/std@$STD_VERSION/collections/chunk.ts";
* import { assertEquals } from "https://deno.land/std@$STD_VERSION/testing/asserts.ts";
*
* 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>(array: readonly T[], size: number): T[][] {
if (size <= 0 || !Number.isInteger(size)) {
throw new Error(
`Expected size to be an integer greater than 0 but found ${size}`,
);
}
if (array.length === 0) {
return [];
}
const ret = Array.from<T[]>({ length: Math.ceil(array.length / size) });
let readIndex = 0;
let writeIndex = 0;
while (readIndex < array.length) {
ret[writeIndex] = array.slice(readIndex, readIndex + size);
writeIndex += 1;
readIndex += size;
}
return ret;
}