Chunk an array in TypeScript
Splits an array into fixed-size pieces, generic in the element.
function chunk<T>(items: T[], size: number): T[][] {
if (size < 1) throw new Error("size must be positive");
const out: T[][] = [];
for (let i = 0; i < items.length; i += size) {
out.push(items.slice(i, i + size));
}
return out;
}
Keywords and builtins used here
Tconstforfunctionifletnumberreturnthrow
The run, in numbers
- Lines
- 8
- Characters to type
- 230
- Tokens
- 87
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 50 seconds.
Step 9 of 11 in Generic helpers, step 17 of 20 in Generics.