| name | mongez-reinforcements-random |
| description | Random value generation via the Random namespace class from @mongez/reinforcements — integers, floats, booleans, strings, UUIDs, nanoids, dates, colors, weighted picks, and seedable deterministic mode.
|
Random
Namespace class — every method is public static. Not instantiable.
import { Random, type RandomDateOptions, type WeightedItem } from "@mongez/reinforcements";
Seeding (reproducible mode)
Random.seed(seed?: number): void
Switches the RNG to a deterministic mulberry32 PRNG. Call with no args (or undefined) to restore Math.random.
Random.seed(42);
const a = Random.int(1, 1000);
Random.seed(42);
const b = Random.int(1, 1000);
a === b;
Random.seed();
Great for fixture-based tests:
beforeEach(() => Random.seed(123));
afterEach(() => Random.seed());
Primitives
Random.int(min?: number, max?: number): number
Random.float(min?: number, max?: number, precision?: number): number
Random.bool(): boolean
Random.int(1, 10);
Random.float(0, 1, 2);
Random.bool();
Strings & ids
Random.string(length?: number): string
Random.id(length?: number, startsWith?: string): string
Random.uuid(): string
Random.nanoid(size?: number): string
Random.token(bytes?: number): string
Random.string(8);
Random.id();
Random.id(4, "user-");
Random.uuid();
Random.nanoid(10);
Random.token(16);
uuid / token use crypto.randomUUID / crypto.getRandomValues when available, falling back to the internal PRNG otherwise. Use for ids only, not for cryptography.
Dates & colors
Random.date(options?: RandomDateOptions): Date
type RandomDateOptions = { min?: Date; max?: Date };
Random.color(): string
Random.date({ min: new Date("2020-01-01"), max: new Date("2024-12-31") });
Random.color();
Pick / sample / weighted
Random.pick<T>(array: readonly T[]): T | undefined
Random.sample<T>(array: readonly T[], n: number): T[]
Random.weighted<T>(items: readonly WeightedItem<T>[]): T | undefined
type WeightedItem<T> = { value: T; weight: number };
Random.pick(["a", "b", "c"]);
Random.sample([1, 2, 3, 4, 5], 3);
Random.weighted([
{ value: "free", weight: 80 },
{ value: "premium", weight: 19 },
{ value: "vip", weight: 1 },
]);
sample returns at most array.length items. Negative weights in weighted are clamped to 0; if every weight is 0 returns undefined.
Gotchas
Random is not instantiable — new Random() is a TS error. Use the static methods directly.
- The legacy aliases
Random.integer / Random.boolean from v2 are removed. Use Random.int / Random.bool.
- Seeded mode persists until cleared — call
Random.seed() (no args) in afterEach to avoid cross-test contamination.