Add some random functions (which I'm already using whoops)
This commit is contained in:
parent
7b5e9b564d
commit
fe096436da
16
js/util.js
16
js/util.js
@ -4,10 +4,26 @@ import * as fflate from './vendor/fflate.js';
|
|||||||
export class LLError extends Error {}
|
export class LLError extends Error {}
|
||||||
|
|
||||||
// Random choice
|
// 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) {
|
export function random_choice(list) {
|
||||||
return list[Math.floor(Math.random() * list.length)];
|
return list[Math.floor(Math.random() * list.length)];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function random_shuffle(list) {
|
||||||
|
// Knuth–Fisher–Yates, 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) {
|
export function setdefault(map, key, defaulter) {
|
||||||
if (map.has(key)) {
|
if (map.has(key)) {
|
||||||
return map.get(key);
|
return map.get(key);
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user