When working in Javascript, I have a simple for loop that increments based on a variable num
, which can be any input number:
const sequenceArr = [];
for (let i = 0; i <= num; i++) {
const addedSum = i + i;
sequenceArr.push({ i, addedSum });
}
For example, if num
is set to 1000, an array of objects up to 1000 will be generated where each object looks like this:
[{1, 2}, {2, 4}, {3, 6} ... {1000, 2000} ]
. If we need to extend the count to 2000, currently the for loop starts over from 0 and repeats the same operations on numbers it has already encountered. This approach seems inefficient. How can I continue the count from, say, 1001 (or the last number in sequenceArr
) instead of starting fresh from 0 and counting all the way up to 2000? Would sending data to a backend and importing a JSON file help with this situation? How could I implement such a solution?
This question relates to a small side project where I am counting up to a certain number so I can perform the addedSum
operation on i
. Upon further inspection, it is clear that the sequenceArr remains constant, so there's no need to recalculate the same numbers repeatedly. Instead, existing numbers should be used if num
is less than the length of our array, while new numbers should only be generated when necessary.
In order to update the sequence with any new continuations of the count, these additional numbers would need to be pushed or updated in the sequenceArr.