Skip to content

Instantly share code, notes, and snippets.

@jonurry
Last active February 28, 2018 15:51
Show Gist options
  • Select an option

  • Save jonurry/48ad237b6ef95b31abd11304ea58b731 to your computer and use it in GitHub Desktop.

Select an option

Save jonurry/48ad237b6ef95b31abd11304ea58b731 to your computer and use it in GitHub Desktop.
6.3 Iterable Groups (Eloquent JavaScript Solutions)
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
@jonurry
Copy link
Author

jonurry commented Feb 28, 2018

6.3 Iterable groups

Make the Group class 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.iterator method 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.

@jonurry
Copy link
Author

jonurry commented Feb 28, 2018

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