weed-sim / src /shared /rng.ts
Yufok1
Checkpoint Devvit v0.0.24
1a343cd
Raw
History Blame Contribute Delete
571 Bytes
export type RandomSource = () => number;
export function randomChoice<T>(items: readonly T[], rng: RandomSource = Math.random): T {
if (items.length === 0) {
throw new Error('Cannot choose from an empty list');
}
const index = Math.min(items.length - 1, Math.floor(rng() * items.length));
return items[index] as T;
}
export function newId(prefix = 'seed'): string {
const cryptoId = globalThis.crypto?.randomUUID?.();
if (cryptoId) {
return cryptoId;
}
return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
}