Skip to content

Instantly share code, notes, and snippets.

@webstrand
Created March 16, 2026 21:37
Show Gist options
  • Select an option

  • Save webstrand/a3bc9c991ed85078259a46b68d314e13 to your computer and use it in GitHub Desktop.

Select an option

Save webstrand/a3bc9c991ed85078259a46b68d314e13 to your computer and use it in GitHub Desktop.
/** branded string representing an html id */
export type id = string & import("./id.private.mjs").id;
/** Knuth LCG multiplier for m=2**32 */
const A = 1664525;
/** LCG increment; Hull–Dobell full-period prime (Numerical Recipes 2e, §7.1). */
const C = 1013904223;
/** LCG internal state */
let state = (Date.now() ^ (Math.random() * 0xffffffff)) >>> 0; // ensure unsigned 32-bit
/** Generate a unique non-monotonic id string */
export function nextId(): id {
const val = `u-${state.toString(36)}` as id;
state = (Math.imul(A, state) + C) >>> 0; // >>> 0 keeps it in uint32
return val;
}
/**
* Given N, constructs a tuple [...P, ...T[P.length:N]] of total length N using elements from T
*
* @typeParam N - Constructed tuple total length
* @typeParam T - Source array to pick element types from, may be tuple
* @typeParam P - Initial prefix, length must be <= N, decides mutability
*/
type Tuple<
N extends number,
T extends readonly unknown[],
P extends readonly unknown[] = T extends any[] ? [] : readonly [],
> = P["length"] extends N
? P
: Tuple<
N,
T,
P extends any[] ? [...P, T[P["length"]]] : readonly [...P, T[P["length"]]]
>;
/** Generate {@link n} unique non-monotonic ids at once and return them as a tuple */
export function takeId<N extends number>(
n: N,
): number extends N ? readonly id[] : Tuple<N, id[]> {
const out: id[] = [];
for (let i = 0; i < n; i++) {
out[i] = `u-${state.toString(36)}` as id;
state = (Math.imul(A, state) + C) >>> 0;
}
return out as never;
}
declare class id {
#private;
}
export type { id };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment