Skip to content

Instantly share code, notes, and snippets.

@royling
Last active August 29, 2015 14:27
Show Gist options
  • Save royling/71b395ae7f2f3a6ee833 to your computer and use it in GitHub Desktop.
Save royling/71b395ae7f2f3a6ee833 to your computer and use it in GitHub Desktop.
Implement an iterable and make the iterators also iterable which leads to continuable iteration
class YourConstruct {
constructor() {}
// implement iterable protocol
[Symbol.iterator]() {
// return an iterator
return {
// the iterator is iterable!
[Symbol.iterator]() {
return this;
}
next() {
// ...
// return {value: any, done: boolean}
}
};
}
}
let yourConstruct = new YourConstruct();
// ...
for (let v of yourConstruct) {
// ...
}
let iterator = yourConstruct[Symbol.iterator]();
console.log(iterator[Symbol.iterator]() === iterator); // => true
for (let x of iterator) {
console.log(x);
break;
}
// continue iteration in another loop
for (let y of iterator) {
console.log(y);
}

The magic why it can continue the iteration in another loop instead of restarting the iteration each time is that: A single iterator instance is returned that is also iterable to iterate the construct.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment