-
-
Save tinovyatkin/839b92e3a07b64e507c83b439953304b to your computer and use it in GitHub Desktop.
Fibonacci ES6 Generator
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 *fibonacci(n) { | |
const infinite = !n && n !== 0; | |
let current = 0; | |
let next = 1; | |
while (infinite || n--) { | |
yield current; | |
[current, next] = [next, current + next]; | |
} | |
} |
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 *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); | |
} |
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
let [...first10] = fibonacci(10); | |
console.log(first10); | |
// [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment