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
54 lines (46 loc) · 940 Bytes
/
06_3_iterable_groups.js
File metadata and controls
54 lines (46 loc) · 940 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
class Group {
#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.#members);
}
}
class GroupIterator {
constructor(members) {
this.#members = members;
this.#position = 0;
}
next() {
if (this.#position >= this.#members.length) {
return {done: true};
} else {
let result = {value: this.#members[this.#position],
done: false};
this.#position++;
return result;
}
}
}
for (let value of Group.from(["a", "b", "c"])) {
console.log(value);
}
// → a
// → b
// → c