Skip to content

Instantly share code, notes, and snippets.

@sematgt

sematgt/iterator.js

Created May 8, 2020
Embed
What would you like to do?
JS iterators tutorial source code simonbliznyuk.com
class Group {
constructor() {
this.elements = [];
}
add(element) {
if (!this.has(element)) {
this.elements.push(element);
}
}
delete(element) {
this.elements.filter(e => e !== element);
}
has(element) {
return this.elements.includes(element);
}
[Symbol.iterator]() {
return new GroupIterator(this);
}
}
class GroupIterator {
constructor(group) {
this.group = group;
this.currentIndex = 0;
}
next() {
if (this.currentIndex === this.group.elements.length) {
return { done: true };
}
let currentValue = {
value: this.group.elements[this.currentIndex],
done: false
};
this.currentIndex++;
return currentValue;
}
}
let group = new Group();
for (let e of [1, 2, 3, 4, 5]) group.add(e);
console.log(group);
for (let value of group) console.log(value);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment