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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
|
function dump(item) {
try {
return JSON.stringify(item);
} catch(e) {
var ret = [];
for (var i in item) {
var j = item[i];
if (typeof j === 'string' || typeof j === 'number') {
ret.push(i + ': ' + j);
} else {
ret.push(i + ': [?]');
}
}
return ret.join(', ');
}
}
function dumpKeys(item) {
var ret = [];
for (var i in item) {
var j = item[i];
if (typeof j === 'string' || typeof j === 'number') {
ret.push(i + ': ' + j);
} else {
ret.push(i + ': [?]');
}
}
return ret.join(', ');
}
function assertEq(a, b) {
if (a !== b) {
print("Stack: " + new Error().stack);
throw "Should have been equal: " + a + " : " + b;
}
}
function assertTrue(a) {
assertEq(!!a, true);
}
function dedup(items, ident) {
var seen = {};
if (ident) {
return items.filter(function(item) {
if (seen[item[ident]]) return false;
seen[item[ident]] = true;
return true;
});
} else {
return items.filter(function(item) {
if (seen[item]) return false;
seen[item] = true;
return true;
});
}
}
function range(size) {
var ret = [];
for (var i = 0; i < size; i++) ret.push(i);
return ret;
}
function searchable() {
var ret = {};
for (var i = 0; i < arguments.length; i++) {
ret[arguments[i]] = 0;
}
return ret;
}
function walkJSON(item, func) {
func(item);
for (x in item) {
if (typeof item[x] === 'object') {
walkJSON(item[x], func);
}
}
}
function keys(x) {
var ret = [];
for (a in x) ret.push(a);
return ret;
}
function values(x) {
var ret = [];
for (a in x) ret.push(x[a]);
return ret;
}
function sum(x) {
return x.reduce(function(a,b) { return a+b }, 0);
}
function sumTruthy(x) {
return x.reduce(function(a,b) { return (!!a)+(!!b) }, 0);
}
function loopOn(array, func) {
for (var i = 0; i < array.length; i++) {
func(i, array[i]);
}
}
// Splits out items that pass filter. Returns also the original sans the filtered
function splitter(array, filter) {
var splitOut = array.filter(filter);
var leftIn = array.filter(function(x) { return !filter(x) });
return { leftIn: leftIn, splitOut: splitOut };
}
|