-
-
Notifications
You must be signed in to change notification settings - Fork 127
/
lib.js
90 lines (80 loc) · 2 KB
/
lib.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
/**
* Library of simple functions for use in all other modules.
* This libary should be clean and not depend on any other modules.
*/
/**
Find the first x in `values` that's larger than `cur`.
Cycle to first value if no larger value is found.
`values` should be sorted in ascending order.
*/
export function findNext(cur, values, slack = 0) {
for (let i = 0; i < values.length; i++) {
let x = values[i];
if (cur < x) {
if (x - cur < slack) {
// Consider `cur` practically equal to `x`
continue;
} else {
return x;
}
}
}
return values[0]; // cycle
}
export function findPrev(cur, values, slack = 0) {
let i = 0;
for (;i < values.length; i++) {
let x = values[i];
if (x + slack >= cur) {
break;
}
}
let target_i = i - 1;
if (target_i < 0) {
target_i = values.length - 1;
}
return values[target_i];
}
export function arrayEqual(a, b) {
if (a === b)
return true;
if (!a || !b)
return false;
if (a.length !== b.length)
return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i])
return false;
}
return true;
}
/** Is the floating point numbers equal enough */
export function eq(a, b, epsilon = 0.00000001) {
return Math.abs(a - b) < epsilon;
}
export function swap(array, i, j) {
let temp = array[i];
array[i] = array[j];
array[j] = temp;
}
export function in_bounds(array, i) {
return i >= 0 && i < array.length;
}
export function indent(level, str) {
let blank = "";
for (let i = 0; i < level; i++) {
blank += " ";
}
return blank + str;
}
export function sum(array) {
return array.reduce((a, b) => a + b, 0);
}
export function zip(...as) {
let r = [];
let minLength = Math.min(...as.map(x => x.length));
for (let i = 0; i < minLength; i++) {
r.push(as.map(a => a[i]));
}
return r;
}