Skip to content

Instantly share code, notes, and snippets.

@zlatkov
Created March 11, 2021 12:56
Show Gist options
  • Save zlatkov/979d22681c0fb434b5283125758f3db3 to your computer and use it in GitHub Desktop.
Save zlatkov/979d22681c0fb434b5283125758f3db3 to your computer and use it in GitHub Desktop.
async function* makeFibonacciSequenceGenerator(endIndex = Infinity) {
let previousNumber = 0;
let currentNumber = 1;
for (let currentIndex = 0; currentIndex < endIndex; currentIndex++) {
await new Promise(resolve => setTimeout(resolve, 1000)); // a simple timeout as an example.
yield currentNumber;
let nextNumber = currentNumber + previousNumber;
previousNumber = currentNumber;
currentNumber = nextNumber;
}
}
(async () => {
const fibonacciSequenceGenerator = makeFibonacciSequenceGenerator(6);
for await (let x of fibonacciSequenceGenerator) {
console.log(x); // 1, then 1, then 2, then 3, then 5, then 8 (with delay in between).
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment