Cotton code
68 lines · 2.2 KB · TypeScriptRaw
/** * The seed's one source of chance: a fixed seed in, the same stream out, on * every machine and every run. Ids come from the seed too (`idOf`), so a * second run names every row exactly as the first did and an import of it * changes nothing. */import { createHash } from "node:crypto";/** mulberry32 over a 32-bit state taken from the seed's hash. */export class Rng {  private state: number;  constructor(seed: string) {    this.state = createHash("sha256").update(seed).digest().readUInt32LE(0);  }  /** A float in [0, 1). */  next(): number {    this.state = (this.state + 0x6d2b79f5) >>> 0;    let t = this.state;    t = Math.imul(t ^ (t >>> 15), t | 1);    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;  }  /** A whole number in [lo, hi]. */  int(lo: number, hi: number): number {    return lo + Math.floor(this.next() * (hi - lo + 1));  }  chance(p: number): boolean {    return this.next() < p;  }  pick<T>(list: readonly T[]): T {    if (!list.length) throw new Error("pick from an empty list");    return list[Math.floor(this.next() * list.length)]!;  }  /** `n` distinct items of `list`, in the stream's order. */  some<T>(list: readonly T[], n: number): T[] {    return this.shuffle(list).slice(0, Math.min(n, list.length));  }  shuffle<T>(list: readonly T[]): T[] {    const out = [...list];    for (let i = out.length - 1; i > 0; i -= 1) {      const j = Math.floor(this.next() * (i + 1));      [out[i], out[j]] = [out[j]!, out[i]!];    }    return out;  }  /** A child stream, so one part's draws never shift another's. */  fork(label: string): Rng {    return new Rng(`${this.next()}:${label}`);  }}/** A row's id as a uuid, from the seed, its table and its place: the same on every run. */export function idOf(seed: string, table: string, n: number | string): string {  const h = createHash("sha256").update(`dev-seed:${seed}:${table}:${n}`).digest("hex");  return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-${((parseInt(h.slice(16, 17), 16) & 3) | 8).toString(16)}${h.slice(17, 20)}-${h.slice(20, 32)}`;}export function sha256(bytes: Uint8Array | string): string {  return createHash("sha256").update(bytes).digest("hex");}