Add some random functions (which I'm already using whoops)

This commit is contained in:
Eevee (Evelyn Woods) 2024-05-06 22:06:56 -06:00
parent 7b5e9b564d
commit fe096436da

View File

@ -4,10 +4,26 @@ import * as fflate from './vendor/fflate.js';
export class LLError extends Error {}
// Random choice
export function random_range(a, b = null) {
if (b === null) {
b = a;
a = 0;
}
return a + Math.floor(Math.random() * (b - a));
}
export function random_choice(list) {
return list[Math.floor(Math.random() * list.length)];
}
export function random_shuffle(list) {
// KnuthFisherYates, of course
for (let i = list.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[list[i], list[j]] = [list[j], list[i]];
}
}
export function setdefault(map, key, defaulter) {
if (map.has(key)) {
return map.get(key);