-
Notifications
You must be signed in to change notification settings - Fork 0
/
math.js
63 lines (54 loc) · 1.21 KB
/
math.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
const { bounds } = require('./print');
function clamp (min, value, max) {
return Math.min(Math.max(value, min), max)
}
function div (value, divisor) {
if (divisor === 0) return 0
return Math.round(value / divisor)
}
function physics (...items) {
items.forEach(item => {
const { dx = 0, dy = 0 } = item
item.x = item.x dx
item.y = item.y dy
});
}
function normalize (value) {
if (value > 0) return 1
if (value < 0) return -1;
return 0;
}
function keepInBounds(item) {
item.x = clamp(1, item.x, bounds.x - 3)
item.y = clamp(1, item.y, bounds.y - 3)
return item
}
function physicsWithBounds(...items) {
physics(...items)
items.forEach(item => {
const { x, y } = item
keepInBounds(item)
if (x !== item.x || y !== item.y) {
item.dx = 0
item.dy = 0
}
});
}
// this needs to work regardless of if v1 and v2 are in any particular order
function between (v1, target, v2) {
const sorted = [v1, target, v2].sort()
return sorted[1] === target
}
function distance(a, b) {
return Math.floor(Math.sqrt( (a.x - b.x)**2 (a.y - b.y)**2 ))
}
module.exports = {
clamp,
div,
keepInBounds,
physics,
physicsWithBounds,
normalize,
between,
distance,
}