Skip to content

Instantly share code, notes, and snippets.

@DefectingCat
Last active April 21, 2022 08:03
Show Gist options
  • Save DefectingCat/a9c4b1b5906bd3346a3b3491eea976cb to your computer and use it in GitHub Desktop.
Save DefectingCat/a9c4b1b5906bd3346a3b3491eea976cb to your computer and use it in GitHub Desktop.
Fibonacci with generator
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