-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.js
90 lines (76 loc) · 1.92 KB
/
util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
function createCanvas(width, height) {
const new_canvas = document.createElement('canvas')
new_canvas.width = width
new_canvas.height = height
document.body.appendChild(new_canvas)
return new_canvas
}
function createButton(callback, text) {
const btn = document.createElement('button')
btn.innerHTML = text
btn.addEventListener('click', callback)
return btn
}
function random(arg1, arg2) {
if(Array.isArray(arg1)) {
return arg1[Math.floor(Math.random() * arg1.length)]
} else {
return Math.random() * (arg2 - arg1) + arg1
}
}
function map(n, in_from, in_to, out_from, out_to) {
return out_from + (n - in_from) / (in_to - in_from) * (out_to - out_from);
}
function hueToRgb(h) {
const mod = (number, limit) => (number < 0 ? number + limit : number % limit)
const h2rgb = (initT) => {
const t = mod(initT, 1)
if (t < 1 / 6) {
return 6 * t
}
if (t < 1 / 2) {
return 1
}
if (t < 2 / 3) {
return ((2 / 3) - t) * 6
}
return 0
}
const r = h2rgb(h + (1 / 3))
const g = h2rgb(h)
const b = h2rgb(h - (1 / 3))
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]
}
function clamp(value, min, max) {
return value < min ? min : value > max ? max : value;
}
function gradient(c1, c2, n) {
n = clamp(n, 0, 1)
return [
c1[0] + (c2[0] - c1[0]) * n,
c1[1] + (c2[1] - c1[1]) * n,
c1[2] + (c2[2] - c1[2]) * n
]
}
function chance(p) {
return Math.random() < p
}
function weightedChooseDo(...items) {
let r = Math.random() * items.reduce((a, [p, _]) => a + p, 0)
for (const [p, f] of items) {
if (r < p)
f()
r -= p;
}
}
export {
random,
createCanvas,
createButton,
map,
clamp,
hueToRgb,
gradient,
chance,
weightedChooseDo
}