OPTION 1 USING GENERATOR FUNCTIONS
I think the proper way to do this is to use a Generator function.
Theese are functions meant to return sequences, they are built for this kinds of situations where you have a sequence that you can calculate based on a formula and want to get the next value at will.
So lets say you have a simple formula to calculate the nth fibonacci number
function fibonacci(n = 0) {
if (n < 0){ throw 'Fibonacci not defined for negative numbers'}
if (n < 2) { return n};
return fibonacci(n - 1) + fibonacci(n - 2);
}
so then you just wrap it in a generator function (using the function* syntax, note the *)
function* fibonacciGenerator() {
var index = 0;
while (true){
// yields the next fibonacci
yield fibonacci(index++);
}
}
Then you can use it creating a new generator and calling the next function to retrieve the next element in the sequence. Note the while true here represents that the sequence is infinite, that is that it never ends and I can keep getting more and more elements. This does not become an infinite loop because of the yield keyword
let fibonacciSequence = fibonacciGenerator();
fibonacciSequence.next().value; // 0
fibonacciSequence.next().value; // 1
fibonacciSequence.next().value; // 1
fibonacciSequence.next().value; // 2
You can read more about generator functions here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
NOT USING GENERATOR FUNCTIONS
If you are not familiar with generator functions or cannot use them, you can do it with a regular function and save the "state". I dont recommend at all saving it in a global variable because its a considered bad practice. But you can create a closure.
Closures are like functions with their own scope, or environment where they can have variables.
function fibonacciGenerator() {
var index = 0;
return function () {
return fibonacci(index++);
}
}
then use it
let fibonacciSequence = fibonacciGenerator();
fibonacciSequence(); // 0
fibonacciSequence(); // 1
fibonacciSequence(); // 1
fibonacciSequence(); // 2
note that the structure is similar than that of generators, but we have normal functions instead.
You can read more about closures here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
number1andnumber2. Then you can just update them each time you call.