shenku
shenku

Reputation: 12438

Dynamic Javascript condition in For loop

Please review the code below, note the condition of my for loop depends on the step parameter.

Rather than every time the condition is executed it determines which branch to use, I would like to test that once - I had supposed I could create a delegate or of the condition but it doesn't seem to work.

Is it possible in JS to do this?

Code:

function(start, end, step) {
  if (step === undefined) {
    step = 1;
  }

  var result = [];
  for (; (step < 0) ? start >= end : start <= end; start += step) {
    result.push(start);
  }

  return result;
}

My attempt:

function(start, end, step) {
  if (step === undefined) {
    step = 1;
  }

  var condition = (step < 0) ? start >= end : start <= end;
  var result = [];
  for (; condition; start += step) {
    result.push(start);
  }

  return result;
}

Upvotes: 0

Views: 1384

Answers (1)

GreenGiant
GreenGiant

Reputation: 5236

To do this, you need to make condition a function, like below. But even if you do, the condition is still executed at every iteration of the loop.

  var condition = (step < 0) ?
      function(start){
          return start >= end;
      } :
      function(start){
          return start <= end;
      };
  var result = [];
  for (; condition(start); start += step) {
    result.push(start);
  }

Upvotes: 2

Related Questions