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.
Last active
August 29, 2015 14:27
-
-
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
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 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} | |
} | |
}; | |
} | |
} |
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
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment