-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path7_3_PGroup.js
52 lines (48 loc) · 1.03 KB
/
7_3_PGroup.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
class GroupIterator {
constructor(group) {
this.i = 0;
this.group = group;
}
next() {
if (this.i === this.group.list.length) return { done: true };
const result = { value: this.group.list[this.i], done: false };
this.i++;
return result;
}
}
class PGroup {
constructor(list) {
this.list = list;
}
add(elt) {
if (!this.has(elt)) return new PGroup(this.list.concat(elt));
return this;
}
delete(elt) {
if (this.has(elt)) return new PGroup(this.list.slice(this.list.indexOf(elt), 1));
return this;
}
has(elt) {
return this.list.indexOf(elt) !== -1;
}
static from(iterable) {
let result = new PGroup();
for (const elt of iterable) {
result.add(elt);
}
return result;
}
[Symbol.iterator]() {
return new GroupIterator(this);
}
}
PGroup.empty = new PGroup([]);
let a = PGroup.empty.add('a');
let ab = a.add('b');
let b = ab.delete('a');
console.log(b.has('b'));
// → true
console.log(a.has('b'));
// → false
console.log(b.has('a'));
// → false