forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06_3_iterable_groups.js
More file actions
56 lines (48 loc) · 954 Bytes
/
06_3_iterable_groups.js
File metadata and controls
56 lines (48 loc) · 954 Bytes
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
class Group {
constructor() {
this.members = [];
}
add(value) {
if (!this.has(value)) {
this.members.push(value);
}
}
delete(value) {
this.members = this.members.filter(v => v !== value);
}
has(value) {
return this.members.includes(value);
}
static from(collection) {
let group = new Group;
for (let value of collection) {
group.add(value);
}
return group;
}
[Symbol.iterator]() {
return new GroupIterator(this);
}
}
class GroupIterator {
constructor(group) {
this.group = group;
this.position = 0;
}
next() {
if (this.position >= this.group.members.length) {
return {done: true};
} else {
let result = {value: this.group.members[this.position],
done: false};
this.position++;
return result;
}
}
}
for (let value of Group.from(["a", "b", "c"])) {
console.log(value);
}
// → a
// → b
// → c