Created
February 6, 2020 09:57
-
-
Save achimoraites/772d5f95bd91756962b690d2f82df243 to your computer and use it in GitHub Desktop.
Generate fibonacci numbers using generators in Javascript
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
/** | |
* Generate fibnacci numbers using generators | |
* A simple illustration of the power that generators | |
* can bring in our code | |
* | |
* generator is from the https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators | |
*/ | |
function* fibonacci() { | |
let fn1 = 0; | |
let fn2 = 1; | |
while (true) { | |
let current = fn1; | |
fn1 = fn2; | |
fn2 = current + fn1; | |
let reset = yield current; | |
if (reset) { | |
fn1 = 0; | |
fn2 = 1; | |
} | |
} | |
} | |
function nthFib(n) { | |
const fibgen = fibonacci(); | |
let fib = 0; | |
for (let o = 0; o <= n; o++) { | |
fib = fibgen.next().value; | |
console.log('number', o, 'fib', fib); | |
} | |
return fib; | |
} | |
/** | |
* Find the nth Fibonacci of 50 | |
*/ | |
const finalFib = nthFib(50); | |
console.log('result is', finalFib); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👏 Nicely done!