Last active
September 23, 2018 00:22
-
-
Save nem035/5b90a144ce2423afb37ed567986cfec7 to your computer and use it in GitHub Desktop.
This file contains 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 * 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