Last active
February 28, 2018 15:51
-
-
Save jonurry/48ad237b6ef95b31abd11304ea58b731 to your computer and use it in GitHub Desktop.
6.3 Iterable Groups (Eloquent JavaScript Solutions)
This file contains hidden or 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
| class Group { | |
| constructor() { | |
| this.group = []; | |
| } | |
| add(item) { | |
| if (!this.group.includes(item)) { | |
| this.group.push(item); | |
| } | |
| } | |
| delete(item) { | |
| let index = this.group.indexOf(item); | |
| if (index !== -1) { | |
| this.group.splice(index, 1); | |
| } | |
| } | |
| has(item) { | |
| return this.group.includes(item); | |
| } | |
| static from(a) { | |
| let g = new Group(); | |
| for (let item of a) { | |
| g.add(item); | |
| } | |
| return g; | |
| } | |
| [Symbol.iterator]() { | |
| return new GroupIterator(this); | |
| }; | |
| } | |
| class GroupIterator { | |
| constructor(o) { | |
| this.i = 0; | |
| this.group = o.group; | |
| } | |
| next() { | |
| if (this.i == this.group.length || this.i > 10) return {done: true}; | |
| let value = this.group[this.i]; | |
| this.i++; | |
| return {value, done: false}; | |
| } | |
| } | |
| for (let value of Group.from(["a", "b", "c"])) { | |
| console.log(value); | |
| } | |
| // → a | |
| // → b | |
| // → c |
Author
Author
Hints
It is probably worthwhile to define a new class GroupIterator. Iterator instances should have a property that tracks the current position in the group. Every time next is called, it checks whether it is done, and if not, moves past the current value and returns it.
The Group class itself gets a method named by Symbol.iterator which, when called, returns a new instance of the iterator class for that group.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
6.3 Iterable groups
Make the
Groupclass from the previous exercise iterable. Refer back to the section about the iterator interface earlier in the chapter if you aren’t clear on the exact form of the interface anymore.If you used an array to represent the group’s members, don’t just return the iterator created by calling the
Symbol.iteratormethod on the array. That would work, but defeats the purpose of this exercise.It is okay if your iterator behaves strangely when the group is modified during iteration.