Skip to content

Instantly share code, notes, and snippets.

@Woozl
Created June 27, 2022 01:58
Show Gist options
  • Save Woozl/8a30ee458715e7b911edf72670ba69d5 to your computer and use it in GitHub Desktop.
Save Woozl/8a30ee458715e7b911edf72670ba69d5 to your computer and use it in GitHub Desktop.
Generates the Fibonacci sequence using Iterable function
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