Skip to content

Instantly share code, notes, and snippets.

@gaurang847
Last active June 19, 2019 19:53
Show Gist options
  • Save gaurang847/c8cf43e22ed956ecff2fc1c13effea6b to your computer and use it in GitHub Desktop.
Save gaurang847/c8cf43e22ed956ecff2fc1c13effea6b to your computer and use it in GitHub Desktop.
function* fibonacciGenerator(){ //the * indicates it's a generator function
//i.e. a function that returns a generator object
yield 0; //first time next() is called
//it'll return with value=0
yield 1; //second time it'll return with value=1
let penultimate = 0, ultimate = 1;
let next = penultimate + ultimate;
while (true){
yield next; //on subsequent calls
penultimate = ultimate;
ultimate = next;
next = penultimate + ultimate; //it'll return sum of previous
//2 terms as value
}
}
const fibGen = fibonacciGenerator();
console.log(fibGen.next().value); //0
console.log(fibGen.next().value); //1
console.log(fibGen.next().value); //1
console.log(fibGen.next().value); //2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment