Last active
April 21, 2022 08:03
-
-
Save DefectingCat/a9c4b1b5906bd3346a3b3491eea976cb to your computer and use it in GitHub Desktop.
Fibonacci with 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* fibonacciSquence() { | |
let x = 0, | |
y = 1; | |
for (;;) { | |
yield y; | |
[x, y] = [y, x + y]; | |
} | |
} | |
const fibonacci = (n: number) => { | |
const arr = new Uint8Array(n + 1); | |
let x = 0; | |
for (const i of fibonacciSquence()) { | |
arr[x++] = i; | |
if (n-- <= 0) return arr; | |
} | |
}; | |
console.log(fibonacci(10)); | |
function* take(n: number, iterable: IterableIterator<number>) { | |
const it = iterable[Symbol.iterator](); | |
while (n-- >= 0) { | |
const next = it.next(); | |
if (next.done) return; | |
yield next.value; | |
} | |
} | |
console.log([...take(10, fibonacciSquence())]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment