forked from elixirscript/elixirscript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenum.js
More file actions
116 lines (90 loc) · 2.41 KB
/
Copy pathenum.js
File metadata and controls
116 lines (90 loc) · 2.41 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
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
116
import Erlang from './erlang';
import Kernel from './kernel';
let Enum = {
__MODULE__: Erlang.atom('Enum'),
all__qmark__: function(collection, fun = (x) => x){
let result = Enum.filter(collection, function(x){
return !fun(x);
});
return result === [];
},
any__qmark__: function(collection, fun = (x) => x){
let result = Enum.filter(collection, function(x){
return fun(x);
});
return result !== [];
},
at: function(collection, n, the_default = null){
for (var i = 0; i < collection.length; i++) {
if(i === n){
return collection[i];
}
}
return the_default;
},
count: function(collection, fun = null){
if(fun == null){
return Kernel.length(collection);
}else{
return Kernel.length(collection.filter(fun));
}
},
each: function(collection, fun){
[].forEach.call(collection, fun);
},
empty__qmark__: function(collection){
return Kernel.length(collection) === 0;
},
fetch: function(collection, n){
if(Kernel.is_list(collection)){
if(n < collection.length && n >= 0){
return Erlang.tuple(Erlang.atom("ok"), collection[n]);
}else{
return Erlang.atom("error");
}
}
throw new Error("collection is not an Enumerable");
},
fetch__emark__: function(collection, n){
if(Kernel.is_list(collection)){
if(n < collection.length && n >= 0){
return collection[n];
}else{
throw new Error("out of bounds error");
}
}
throw new Error("collection is not an Enumerable");
},
filter: function(collection, fun){
return [].filter.call(collection, fun);
},
map: function(collection, fun){
return [].map.call(collection, fun);
},
map_reduce: function(collection, acc, fun){
let mapped = Erlang.list();
let the_acc = acc;
for (var i = 0; i < collection.length; i++) {
let tuple = fun(collection[i], the_acc);
the_acc = tuple.get(1);
mapped = Erlang.list(...mapped.concat([tuple.get(0)]))
}
return Erlang.tuple(mapped, the_acc);
},
member: function(collection, value){
for(let x of collection){
if(x === value){
return true;
}
}
return false;
},
reduce: function(collection, acc, fun){
let the_acc = acc;
for (var i = 0; i < collection.length; i++) {
the_acc = fun(collection[i], the_acc);
}
return the_acc;
}
};
export default Enum;