Skip to content

Instantly share code, notes, and snippets.

@jfairbank
Last active December 4, 2023 12:23
Show Gist options
  • Star 32 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save jfairbank/8d36e4bde9c16dc0bac7 to your computer and use it in GitHub Desktop.
Save jfairbank/8d36e4bde9c16dc0bac7 to your computer and use it in GitHub Desktop.
Fibonacci ES6 Generator
function *fibonacci(n) {
const infinite = !n && n !== 0;
let current = 0;
let next = 1;
while (infinite || n--) {
yield current;
[current, next] = [next, current + next];
}
}
function *fibonacci(n = null, current = 0, next = 1) {
if (n === 0) {
return current;
}
let m = n !== null ? n - 1 : null;
yield current;
yield *fibonacci(m, next, current + next);
}
let [...first10] = fibonacci(10);
console.log(first10);
// [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
@AgentCoop
Copy link

The recursive variant could be a bit simpler:

function *fibonacci(n, current = 0, next = 1) {
  if (n === 0) {
    return current;
  }
  yield current;
  yield *fibonacci(n-1, next, current + next);
}

let a = [...fibonacci(20)]
// > Array [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]

@mohanramphp
Copy link

@AgentCoop - simply superb

@jimmywarting
Copy link

jimmywarting commented Sep 28, 2018

Made one myself... tried doing it as small as possible, difference is it won't output 0 and have no ending
and the index 78 is more accurate since it uses BigInt n

index 78 should be 14472334024676221 not 14472334024676220

function* fibonacci(a=0n,b=1n){for(;a=b+(b=a);)yield a}

@talaalm
Copy link

talaalm commented Jun 19, 2020

@AgentCoop

I really like your code and I'd like to know if you can explain your thought process on it. My code is a bit different. I would appreciate some advice. Thanks!

function fibonacciGenerator (n) {
var output = [];
if (n === 1) {
output = [0];
}
else if (n === 2) {
output = [0, 1];
}
else {
output = [0,1];
for (var i = 2; i < n;i++) {
output.push(output[output.length - 2] + output[output.length - 1]);
}
}
return output;
}
var output = fibonacciGenerator(10);
console.log(output);

@dbhatt272
Copy link

var fibonacci_series = function (n)
{
if (n===1)
{
return [0, 1];
}
else
{
var s = fibonacci_series(n - 1);
s.push(s[s.length - 1] + s[s.length - 2]);
return s;
}
};

console.log(fibonacci_series(5));

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