-
-
Save gaurang847/c8cf43e22ed956ecff2fc1c13effea6b 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* 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 | |
} | |
} |
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
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