Skip to content

Instantly share code, notes, and snippets.

@tkshill
Created March 6, 2023 18:15
Show Gist options
  • Save tkshill/516084e1572ca7d93d73a1baf9be81a5 to your computer and use it in GitHub Desktop.
Save tkshill/516084e1572ca7d93d73a1baf9be81a5 to your computer and use it in GitHub Desktop.
Comparing multiple Fibonacci iterators
const fib = (n: number): number => n === 0 ? 0 : n === 1 ? 1 : (fib(n - 1) + fib(n - 2))
console.log(Array.from(Array(21).keys()).map(fib))
const fibgen = function* (n: number) {
if (n < 0) throw RangeError("number cannot be negative")
if (!Number.isInteger(n)) throw TypeError("number should be an integer")
let first = 0, second = 1
yield first
if (n >= 1) yield second
for (let tick = 2; tick <= n; tick++) {
[first, second] = [second, first + second]
yield second
}
}
console.log([...fibgen(20)])
function fibArray(n: number) {
const fib = [0, 1];
for (let i = 2; i <= n; i++) {
fib.push(fib[i - 1] + fib[i - 2]);
}
return fib;
}
console.log(fibArray(20))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment