Created
March 7, 2018 15:58
-
-
Save adambene/4585786ba6ab571ccbad96460d2d333c to your computer and use it in GitHub Desktop.
Generator, iterator, for...of in JavaScript
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
function* naturals() { | |
let i = 1; | |
while (true) { | |
// it can count to infinity | |
yield i++; | |
} | |
} | |
for (let i of naturals()) { | |
// count only to 5 | |
if (i > 5) { | |
break; | |
} | |
console.log(i); // logs: 1, 2, 3, 4, 5 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment