Skip to content

Instantly share code, notes, and snippets.

@gnab
Created December 10, 2013 12:10
Show Gist options
  • Save gnab/7889651 to your computer and use it in GitHub Desktop.
Save gnab/7889651 to your computer and use it in GitHub Desktop.
Generators.
function* fib () {
var [a, b, n] = [1, 1, 1];
while (true) {
yield [a, n];
[a, b, n] = [b, a + b, n + 1];
}
}
for (let [n, i] of fib()) {
console.log("%d: %d", i, n);
// Break at 10th number
if (i === 10) {
break;
}
}
// =>
// 1: 1
// 2: 1
// 3: 2
// 4: 3
// 5: 5
// 6: 8
// 7: 13
// 8: 21
// 9: 34
// 10: 55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment