-
Notifications
You must be signed in to change notification settings - Fork 2
/
functional.js
69 lines (56 loc) · 1.39 KB
/
functional.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
function slice(from, seq) {
var arr = new Array();
for(var i = from; i < seq.length; i++) {
arr.push(seq[i]);
}
return arr;
}
function shortestof(seqs) {
var shortest = seqs[0].length;
for(var i = 0; i < seqs.length; i++) {
if(seqs[i].length < shortest)
shortest = seqs[i].length;
}
return shortest;
}
function collectargs(index, seqs) {
var collected = new Array();
for(var i = 0; i < seqs.length; i++)
collected.push(seqs[i][index]);
return collected;
}
function map(fn, seq) {
var seqs = slice(1, arguments);
var mapped = new Array();
var args = false;
var i = 0;
var shortest = shortestof(seqs);
while(shortest > i) {
args = collectargs(i, seqs);
mapped.push(fn.apply(null, args));
i++;
}
return mapped;
}
function filter(fn, seq) {
var filtered = new Array();
for(var i = 0; i < seq.length; i++) {
if(fn(seq[i])) {
filtered.push(seq[i]);
}
}
return filtered;
}
function rfilter(fn, seq) {
var filtered = new Array();
for(var i = 0; i < seq.length; i++) {
if(seq[i] && seq[i].length) { //element is a sequence
filtered = filtered.concat(rfilter(fn, seq[i]));
} else {
if(fn(seq[i])) {
filtered.push(seq[i]);
}
}
}
return filtered;
}