-
Notifications
You must be signed in to change notification settings - Fork 1
/
chunks.ts
46 lines (34 loc) · 939 Bytes
/
chunks.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
import type { PrototypeStruct } from '../index.js';
interface Chunks<T> {
chunks(chunkSize: number): T[] | T[][];
}
export const chunks: PrototypeStruct = {
label: 'chunks',
fn: function arrayChunks<T>(chunkSize: number): T[] | T[][] {
const ctx = this as unknown as T[];
const len = ctx.length;
const chunkSizeInt = Number(chunkSize);
if ('number' !== typeof(chunkSize) || chunkSizeInt < 1) {
throw new TypeError(`Expect 'chunkSize' to be a number that is at least 1`);
}
if (!len) return [];
if (1 === len || len === chunkSizeInt) return [ctx];
const set = [];
let subset = [];
let i = chunkSizeInt;
for (const n of ctx) {
if (!i) {
i = chunkSizeInt;
set.push(subset);
subset = [];
}
subset.push(n);
i -= 1;
}
set.push(subset);
return set;
},
};
declare global {
interface Array<T> extends Chunks<T> {}
}