// m01 util: small helpers used by every later module. /** `range(n)` is `[0, 1, ..., n-1]`; `range(0)` is `[]`. * @type {(n: number) => number[]} */ export const range = (n) => Array.from({ length: n }, (_, i) => i) /** `xs` without its last element; an empty list stays empty. Never mutates `xs`. * @type {(xs: A[]) => A[]} */ export const dropLast = (xs) => xs.slice(0, -1) /** True if some element `x` of `xs` satisfies `eq(x, p)`. `eq` lets callers compare structurally (e.g. `pointEquals`). * @type {(xs: A[], p: B, eq: (x: A, p: B) => boolean) => boolean} */ export const contains = (xs, p, eq) => xs.some((x) => eq(x, p)) /** `pipe(x, f, g)` is `g(f(x))`: thread a value through functions left to right. * @type {(x: any, ...fns: ((a: any) => any)[]) => any} */ export const pipe = (x, ...fns) => fns.reduce((acc, f) => f(acc), x) /** `compose(f, g)(x)` is `f(g(x))`: functions applied right to left. * @type {(...fns: ((a: any) => any)[]) => (x: any) => any} */ export const compose = (...fns) => (x) => fns.reduceRight((acc, f) => f(acc), x) /** * Freeze `obj` and everything reachable from it, then return it. * Freezing is the one deliberate "mutation" here: it makes later accidental mutation throw. * We recurse even into children that are already frozen (a frozen parent can still hold * unfrozen children). `ancestors` is the path from the root to `obj`; passing it down * (instead of keeping a shared "seen" set) stops cyclic structures without any mutable state. * @type {(obj: T, ancestors?: unknown[]) => T} */ export const deepFreeze = (obj, ancestors = []) => { if (obj === null || typeof obj !== 'object' || ancestors.includes(obj)) return obj Object.freeze(obj) Object.values(obj).forEach((v) => deepFreeze(v, [...ancestors, obj])) return obj }