-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathiterable.js
More file actions
54 lines (48 loc) · 1.33 KB
/
iterable.js
File metadata and controls
54 lines (48 loc) · 1.33 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
const Iterable = new Protocol({
name: 'Iterable',
requires: {
iterator: Symbol.iterator,
},
provides: Object.getOwnPropertyDescriptors({
forEach(f) {
let i = 0;
for (let entry of this) {
f.call(this, entry, i, this);
++i;
}
},
foldl(fn, memo) {
this[Iterable.forEach](e => { memo = fn(memo, e); });
return memo;
},
// C must implement Applicative and Monoid
foldInto(C) {
if (!(C implements Applicative && C implements Monoid)) {
throw new TypeError('Iterable.foldInto must be given a class which implements both Applicative and Monoid');
}
return this[Iterable.foldl](
(memo, a) => memo[Semigroup.append](C[Applicative.pure](a)),
C[Monoid.empty]
);
},
// ... basically everything in Foldable, except this is from the left
}),
});
const IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));
function Iterator() {}
Iterator.prototype = IteratorPrototype;
IteratorPrototype[Functor.map] = function(fn) {
let iter = this;
// TODO: construct from @@species?
return {
__proto__: IteratorPrototype,
next() {
let r = iter.next();
return r.done ? r : {
value: fn(r.value),
done: false,
};
},
};
};
Protocol.implement(Iterator, Functor);