Last active
August 29, 2015 14:10
-
-
Save montanaflynn/3e4da9c6ce0e83e2acb5 to your computer and use it in GitHub Desktop.
Examples of using ES6 generators
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* counter() { | |
var n = 0; | |
while (true) { | |
yield n++; | |
} | |
} | |
for (var number of counter()) { | |
console.log('counter is at', number); | |
} |
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* fibonacci() { | |
var i = 0, n = 1, keepGoing = true | |
while (keepGoing) { | |
if (i === i/0) { | |
keepGoing = false | |
continue | |
} | |
yield i | |
var t = i | |
i = n | |
n += t | |
} | |
} | |
// Shortcut for firing .next() to get each yielded value | |
for (var i of fibonacci()) { | |
console.log(i) | |
} | |
// You could also do it like this to get the first 50 in the sequence | |
// var fib = fibonacci() | |
// for (var i = 0; i < 50; i++) { | |
// val = fib.next().value | |
// console.log(val) | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment