forked from BKM-team/Blocks
/
utils.js
67 lines (57 loc) · 1.09 KB
/
utils.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
function* map(f, xs) {
for (var x of xs) {
yield f(x);
}
}
function mapM_(f, xs) {
for (var x of xs) {
f(x);
}
}
function forM(xs, f) {
mapM_(f, xs);
}
// performs automatic generator detection
function* lazify(arr) {
if (arr.hasOwnProperty("next")) {
for (var x of arr) {
yield x;
}
} else {
for (var i = 0; i < arr.length; i++) {
yield arr[i];
}
}
}
// this has forced lazify because it's not using for..of
function foldl1(f, xs) {
xs = lazify(xs);
var a = xs.next().value;
var b;
while(b = xs.next(), !b.done) {
a = f(a,b.value);
}
return a;
}
function* filter(pred, xs) {
for (var x of xs) {
if (!pred(x)) {
continue;
}
yield x;
}
}
function seq(lazy) {
var result = [];
if (!lazy) {
return undefined;
}
var next = lazy.next();
while (!next.done) {
result.push(next.value);
next = lazy.next();
}
return result;
}
export default { map, mapM_, forM, filter, foldl1, seq };