-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhelpers.js
More file actions
executable file
·86 lines (71 loc) · 1.43 KB
/
helpers.js
File metadata and controls
executable file
·86 lines (71 loc) · 1.43 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
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
// =============================================================================
// HELPER FUNCTIONS
// Numbers
/**
* Returns a random number between `a` and `b`.
* If `b` is not supplied, returns a random number between 0 and `a`.
*/
function randN(a, b) {
if (b === undefined) {
return Math.random() * a;
}
return (Math.random() * (b - a)) + a;
}
/**
* Like randN, but returns a random *integer*.
*/
function randInt(a, b) {
if (b === undefined) {
return Math.floor(randN(a + 1));
}
return Math.floor(randN(a, b + 1));
}
// Collections
function filter(array, predicate) {
return reduce(array, function(acc, x, i) {
if (predicate(x, i)) {
return conj(acc, x);
}
return acc;
}, []);
}
function map(array, f) {
return reduce(array, function(acc, x, i) {
return conj(acc, f(x, i));
}, []);
}
function reduce(array, f, start) {
var acc = start;
each(array, function(element, i) {
acc = f(acc, element, i);
});
return acc;
}
function each(array, f) {
for (var i = 0; i < array.length; i++) {
f(array[i], i);
}
}
function take(xs, n) {
return xs.slice(0, n);
}
function range(n) {
return n < 0 ? [] : conj(range(n - 1), n);
}
function conj(xs, x) {
xs.push(x);
return xs;
}
function randElt(xs) {
return xs[randInt(xs.length - 1)];
}
function cons(x, xs) {
xs.unshift(x);
return xs;
}
function rest(xs) {
return xs.slice(1);
}
function first(xs) {
return xs[0];
}