Last active
July 10, 2023 05:11
-
-
Save stivsk/4230e64f7f6aa02954b8b5260132978f to your computer and use it in GitHub Desktop.
Fibonacci sequence using Generators
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* 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