Skip to content

Instantly share code, notes, and snippets.

@zlatkov
Created March 11, 2021 12:42
Show Gist options
  • Save zlatkov/f690d37341105957407d499e286ef10a to your computer and use it in GitHub Desktop.
Save zlatkov/f690d37341105957407d499e286ef10a to your computer and use it in GitHub Desktop.
function makeFibonacciSequenceIterator(endIndex = Infinity) {
let currentIndex = 0;
let previousNumber = 0;
let currentNumber = 1;
let iterator = {};
iterator[Symbol.iterator] = () => {
return {
next: () => {
if (currentIndex >= endIndex) {
return { value: currentNumber, done: true };
}
const result = { value: currentNumber, done: false };
const nextNumber = currentNumber + previousNumber;
previousNumber = currentNumber;
currentNumber = nextNumber;
currentIndex++;
return result;
}
}
};
return iterator;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment