more random funcs

This commit is contained in:
Chris Wanstrath 2025-09-28 22:14:24 -07:00
parent 0fe73b6f3e
commit 010730127b

View File

@ -19,4 +19,16 @@ export function rng(min: number, max = 0) {
min = Math.ceil(min)
max = Math.floor(max)
return Math.floor(Math.random() * (max - min + 1)) + min
}
// randomElement([5, 7, 9]) #=> 7
export function randomElement<T>(list: T[]): T | undefined {
if (!list.length) return
return list[rng(0, list.length - 1)]
}
// randomIndex([5, 7, 9]) #=> 1
export function randomIndex<T>(list: T[]): number | undefined {
if (!list.length) return
return rng(0, list.length - 1)
}