Files

31 lines
1.5 KiB
JavaScript

// m01 util: small helpers used by every later module.
/** `range(n)` is `[0, 1, ..., n-1]`; `range(0)` is `[]`. */
export const range = (n) => Array.from({ length: n }, (_, i) => i)
/** `xs` without its last element; an empty list stays empty. Never mutates `xs`. */
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`). */
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. */
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. */
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.
*/
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
}