Home > Software design >  How can I loop through two sets of numbers?
How can I loop through two sets of numbers?

Time:04-01

I've got a small puzzle that I can't quite figure out!

I need to loop through two sets of numbers indefinitely, one first and then the other. Both start at -1 and both go up to 2.

firstIndex = -1
secondIndex = -1

I can loop through the first number using:

setInterval(() => {
  if (firstIndex === 2) {
    firstIndex = 0;
  } else {
    firstIndex  
  }
}, 10000);

But I can't figure out how to switch to secondIndex when firstIndex is 2 so that secondIndex goes up to 2, stops, and then firstIndex starts counting up, stops, and then secondIndex starts counting up…

So like this…

firstIndex = 0, firstIndex = 1, firstIndex = 2,
secondIndex = 0 (firstIndex = -1), secondIndex = 1, secondIndex = 2,
firstIndex = 0 (secondIndex = -1), firstIndex = 1, firstIndex = 2,
secondIndex = 0 (firstIndex = -1), secondIndex = 1, secondIndex = 2…

Please help :)

CodePudding user response:

You could take an array and increment the value with a given index until a max value and change the index for incrementing the other inddex, and so on.

let
    data = [0, 0],
    index = 0;

setInterval(() => {
    if (  data[index] > 2) {
        data[index] = 0;
        index = 1 - index;
    }
    console.log(...data);
}, 500);

CodePudding user response:

I would store those indices in an array instead of two variables. That way it is easily extensible to 3 or more indices.

Here is an implementation where there are 3 instead of 2 indices (to better demo the idea). At any start of the timer callback there will be only one index that is not equal to -1:

var max = 2;
var indices = [-1, -1, max]; // put max in last entry

setInterval(() => {
    let i = indices.findIndex(n => n !== -1);
    indices[i]  ;
    if (indices[i] > max) {
        indices[i] = -1;
        indices[(i   1) % indices.length] = 0;
    }
    console.log(...indices);
}, 300);

  • Related