Created
March 6, 2023 18:15
-
-
Save tkshill/516084e1572ca7d93d73a1baf9be81a5 to your computer and use it in GitHub Desktop.
Comparing multiple Fibonacci iterators
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 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