Skip to content

Instantly share code, notes, and snippets.

@montanaflynn
Last active August 29, 2015 14:10
Show Gist options
  • Save montanaflynn/3e4da9c6ce0e83e2acb5 to your computer and use it in GitHub Desktop.
Save montanaflynn/3e4da9c6ce0e83e2acb5 to your computer and use it in GitHub Desktop.
Examples of using ES6 generators
function* counter() {
var n = 0;
while (true) {
yield n++;
}
}
for (var number of counter()) {
console.log('counter is at', number);
}
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