-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
32 lines (27 loc) · 861 Bytes
/
utils.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
const clamp = (a, b, t) => Math.max(a, Math.min(b, t));
const lerp = (a, b, t) => (1 - t) * a + b * t;
const mapRange = ([a, b], [c, d], t) => ((d - c) / (b - a)) * (t - a) + c;
const mapNRange = (a, b, t) => {
let index = 0;
for (let i = 0; i < a.length - 1; i++) {
if (
(t >= a[i] && t <= a[i + 1]) ||
t < a[i] ||
(t > a[i + 1] && i == a.length - 2)
) {
index = i;
break;
}
}
return mapRange([a[index], a[index + 1]], [b[index], b[index + 1]], t);
};
function array(length, transform = (a) => a) {
return Array.from({ length }).map(transform);
}
function round(value, toNearest = 1) {
return Math.round(value / toNearest) * toNearest;
}
function getIndex(value, indexWidth) {
return Math.round(Math.round(value / indexWidth));
}
export { clamp, mapNRange, mapRange, lerp, round, getIndex, array };