Monday, 15 May 2017

Loop through 2 number ranges on javascript

I'm developing a solution on which I need to loop through two separate continuous number ranges. Lets say for example 1 to 5 and 10 to 15.

I'm using the following code:

var X = [];

for (i = 1; i < 6; i++) {
  X.push(i);
}
for (i = 10; i < 16; i++) {
  X.push(i);
}

for (var x in X) {      
  console.log(parseInt(X[x]));
}

This code does the job, but have a lot of overhead and unnecessary operations:

  • Spending time filling array with desired ranges
  • Accessing element by index for getting the true value (X[x])
  • Converting the value back to integer using parseInt (as the type X[x] is string)

Is there any simpler/more efficient way to perform this kind of operation? Something like this:

for(x = 1 to 5, then x = 10 to 15) {
  // do something with x
}


Constraints:

  • Using two separate loops with same code inside is not useful as this loop is repeated on several locations on the code
  • Packaging the contents of the loops inside functions is not desirable
  • Checking for x boundaries and updating its value inside loop is also not desirable (I mean, checking if x == 5 and then changing it to 10)

I've searched through SO but couldn't find any solution for this.

Thanks in advance!



via GCSDC

No comments:

Post a Comment