Created
July 27, 2021 23:38
-
-
Save yitonghe00/249ced3362dfdc20e6e8f2e102f0d15f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Your code here (and the code from the previous exercise) | |
class GroupIterator { | |
constructor(group) { | |
this.group = group; | |
this.i = 0; | |
} | |
next() { | |
if (this.i === this.group.values.length) { | |
return { done: true }; | |
} | |
const value = this.group.values[this.i]; | |
this.i += 1; | |
return { value, done: false }; | |
} | |
} | |
class Group { | |
// Your code here. | |
constructor() { | |
this.values = []; | |
} | |
add(elem) { | |
if (!this.has(elem)) { | |
this.values.push(elem); | |
} | |
} | |
delete(elem) { | |
this.values = this.values.filter(v => v !== elem); | |
} | |
has(elem) { | |
return this.values.includes(elem); | |
} | |
static from(itr) { | |
const g = new Group(); | |
for (let elem of itr) { | |
g.add(elem); | |
} | |
return g; | |
} | |
[Symbol.iterator]() { | |
return new GroupIterator(this); | |
} | |
} | |
for (let value of Group.from(["a", "b", "c"])) { | |
console.log(value); | |
} | |
// → a | |
// → b | |
// → c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment