Created
June 27, 2022 01:58
-
-
Save Woozl/8a30ee458715e7b911edf72670ba69d5 to your computer and use it in GitHub Desktop.
Generates the Fibonacci sequence using Iterable function
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* fib(n: number) { | |
if(n <= 1) { | |
yield 0; | |
} | |
else { | |
let twoBefore = 0, oneBefore = 1; | |
yield twoBefore; | |
yield oneBefore; | |
for(let i = 2; i < n; ++i) { | |
const current = twoBefore + oneBefore; | |
twoBefore = oneBefore; | |
oneBefore = current; | |
yield current; | |
} | |
} | |
} | |
for(const i of fib(6)) console.log(i); // 0 1 1 2 3 5 | |
console.log([...fib(6)]); // [0, 1, 1, 2, 3, 5] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment