Skip to content

Instantly share code, notes, and snippets.

@zlatkov
Created March 11, 2021 12:52
Show Gist options
  • Save zlatkov/f4748c78bc145c4284082fee6f6b83fc to your computer and use it in GitHub Desktop.
Save zlatkov/f4748c78bc145c4284082fee6f6b83fc to your computer and use it in GitHub Desktop.
function* makeFibonacciSequenceGenerator(endIndex = Infinity) {
let previousNumber = 0;
let currentNumber = 1;
let skipCount = 0;
for (let currentIndex = 0; currentIndex < endIndex; currentIndex++) {
if (skipCount === 0) {
skipCount = yield currentNumber; // skipCount is the parameter passed through the invocation of `fibonacciSequenceGenerator.next(value)` below.
skipCount = skipCount === undefined ? 0 : skipCount; // makes sure that there is an input
} else if (skipCount > 0){
skipCount--;
}
let nextNumber = currentNumber + previousNumber;
previousNumber = currentNumber;
currentNumber = nextNumber;
}
}
let fibonacciSequenceGenerator = makeFibonacciSequenceGenerator(50);
console.log(fibonacciSequenceGenerator.next().value); // prints 1
console.log(fibonacciSequenceGenerator.next(3).value); // prints 5 since 1, 2, and 3 are skipped.
console.log(fibonacciSequenceGenerator.next().value); // prints 8
console.log(fibonacciSequenceGenerator.next(1).value); // prints 21 since 13 is skipped.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment