File size: 571 Bytes
1a343cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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)}`;
}