Skip to content

chunk

Edit

Splits an array into fixed-size groups and controls how an incomplete final group is handled.

chunk.ts
export type ChunkOptions = {
remainder?: "keep" | "discard" | "wrap";
};
/** Splits an array into fixed-size groups without mutating the input. */
export const chunk = <const T>(
array: readonly T[],
size: number,
{ remainder = "keep" }: ChunkOptions = {},
): T[][] => {
if (!Number.isSafeInteger(size) || size <= 0) {
throw new RangeError("size must be a positive safe integer");
}
if (remainder !== "keep" && remainder !== "discard" && remainder !== "wrap") {
throw new RangeError("remainder must be keep, discard, or wrap");
}
const values: T[] = [];
for (let index = 0; index < array.length; index += 1) {
if (!Object.hasOwn(array, index)) {
throw new TypeError("array must not contain empty slots");
}
values.push(array[index] as T);
}
if (values.length === 0) return [];
const chunks: T[][] = [];
for (let index = 0; index < values.length; index += size) {
chunks.push(values.slice(index, index + size));
}
const lastChunk = chunks[chunks.length - 1];
if (!lastChunk) return chunks;
if (lastChunk.length === size) return chunks;
if (remainder === "discard") {
chunks.pop();
} else if (remainder === "wrap") {
let sourceIndex = 0;
while (lastChunk.length < size) {
lastChunk.push(values[sourceIndex % values.length] as T);
sourceIndex += 1;
}
}
return chunks;
};
Terminal
wget -O src/lib/chunk.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/chunk.ts
chunk.example.ts
import { chunk } from "./chunk";
const numbers = [1, 2, 3, 4, 5];
const result = chunk(numbers, 2);
// Output: [[1, 2], [3, 4], [5]]
console.log(result);
chunk.2.example.ts
import { chunk } from "./chunk";
const numbers = [1, 2, 3, 4, 5];
const result = chunk(numbers, 2, { remainder: "discard" });
// Output: [[1, 2], [3, 4]]
console.log(result);
chunk.3.example.ts
import { chunk } from "./chunk";
const numbers = [1, 2, 3, 4, 5];
const result = chunk(numbers, 3, { remainder: "wrap" });
// Output: [[1, 2, 3], [4, 5, 1]]
console.log(result);
chunk.4.example.ts
import { chunk } from "./chunk";
const numbers = [1, 2, 3, 4, 5];
const result = chunk(numbers, 3);
// Output: [[1, 2, 3], [4, 5]]
console.log(result);
chunk.5.example.ts
import { chunk } from "./chunk";
const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
const result = chunk(fruits, 2, { remainder: "discard" });
// Output: [['apple', 'banana'], ['cherry', 'date']]
console.log(result);
  • array (readonly T[]) — Dense values to divide into groups. Sparse arrays are rejected.
  • size (number) — Positive safe integer specifying each group’s size.
  • options.remainder ("keep" | "discard" | "wrap", default: "keep") — Keeps the incomplete group, discards it, or fills it by cycling from the beginning of array.

T[][] — New arrays containing the grouped values. The input is not mutated.