Skip to content

Instantly share code, notes, and snippets.

@stivsk
Last active July 10, 2023 05:11
Show Gist options
  • Save stivsk/4230e64f7f6aa02954b8b5260132978f to your computer and use it in GitHub Desktop.
Save stivsk/4230e64f7f6aa02954b8b5260132978f to your computer and use it in GitHub Desktop.
Fibonacci sequence using Generators
function* fibonacciGenerator() {
const sequence = [0, 1];
yield 0;
yield 1;
while (true) {
let i = sequence.length;
sequence[i] = sequence[i - 1] + sequence[i - 2];
yield sequence[i];
}
}
// Create the generator
const fibonacci = fibonacciGenerator();
// Use the new "fibonacci" generator
for (let i = 0; i <= 5; i++) {
console.log(fibonacci.next());
}
// Result:
// { value: 0, done: false }
// { value: 1, done: false }
// { value: 1, done: false }
// { value: 2, done: false }
// { value: 3, done: false }
// { value: 5, done: false }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment