Skip to content

Instantly share code, notes, and snippets.

@nem035
Last active September 23, 2018 00:22
Show Gist options
  • Save nem035/5b90a144ce2423afb37ed567986cfec7 to your computer and use it in GitHub Desktop.
Save nem035/5b90a144ce2423afb37ed567986cfec7 to your computer and use it in GitHub Desktop.
function * fibonacciGen() {
let prev1 = 1;
let prev2 = 1;
while (true) {
let next = prev1 + prev2;
yield prev1;
prev1 = prev2;
prev2 = next;
}
}
const fib = fibonacciGen();
// print first 10 fibonacci numbers
for (let i = 0; i < 10; i++) {
console.log(fib.next().value) // 1 1 2 3 5 8 13 21 34 55
}
// since generators return an Interator
// we can also use for..of on them
// here's another way to print the same result
let limit = 10;
for (const num of fibonacciGen()) {
if (limit === 0) {
break;
}
console.log(num); // 1 1 2 3 5 8 13 21 34 55
limit = limit - 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment