chunk
EditSplits an array into fixed-size groups and controls how an incomplete final group is handled.
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;};Download
Section titled “Download”wget -O src/lib/chunk.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/chunk.tstemp_dir="$(mktemp -d)" && bunx degit jrTilak/lazykit/registry/functions "$temp_dir" && mv "$temp_dir/chunk.ts" src/lib/chunk.ts && rm -r "$temp_dir"Examples
Section titled “Examples”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);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);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);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);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 ofarray.
Returns
Section titled “Returns”T[][] — New arrays containing the grouped values. The input is not mutated.