-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlimit.js
More file actions
50 lines (48 loc) · 1.46 KB
/
limit.js
File metadata and controls
50 lines (48 loc) · 1.46 KB
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
// Limit
// Restricting numbers between two values
// Clamp, Wrap, Fold and Sigmoid are supported
const Limit = (low, high) => {
const [min, max] = low < high ? [low, high] : [high, low];
return {
min, max,
clamp(n) {
if (n < this.min) return this.min;
if (n > this.max) return this.max;
return n;
},
wrap(n) {
const d = this.max - this.min;
return this.min + (n < 0 ? (n%d+d)%d : n%d);
},
fold(n) {
const N = (n - this.min) % (2 * (this.max - this.min)) + this.min;
if (N > this.max) return 2 * this.max - N;
return N;
},
sigmoid(n) {
const d = this.max - this.min;
return d / (1 + Math.exp(4 * (this.min - n) / d + 2)) + this.min;
}
};
};
Limit.clamp = (n, a, b) => {
if (b < a) return Limit.clamp(n, b, a);
if (n < a) return a;
if (n > b) return b;
return n;
};
Limit.wrap = (n, a, b) => {
if (b < a) return Limit.wrap(n, b, a);
const d = b - a;
return this.min + (n < 0 ? (n%d+d)%d : n%d);
};
Limit.fold = (n, a, b) => {
if (b < a) return Limit.fold(n, b, a);
const N = (n - a) % (2 * (b - a)) + a;
if (N > b) return 2 * b - N;
return N;
};
Limit.sigmoid = (n, a, b) => {
if (b < a) return Limit.sigmoid(n, b, a);
return (b - a) / (1 + Math.exp(4 * (a - n) / (b - a) + 2)) + a;
};