Skip to content

Instantly share code, notes, and snippets.

@achimoraites
Created February 6, 2020 09:57
Show Gist options
  • Save achimoraites/772d5f95bd91756962b690d2f82df243 to your computer and use it in GitHub Desktop.
Save achimoraites/772d5f95bd91756962b690d2f82df243 to your computer and use it in GitHub Desktop.
Generate fibonacci numbers using generators in Javascript
/**
* 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);
@gangsthub
Copy link

👏 Nicely done!

@achimoraites
Copy link
Author

Thanks ❤️ !!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment