Moshe
Moshe

Reputation: 58107

Conditionally change the direction of a "for loop"?

Is it possible to conditionally change the direction of a for loop in ActionScript?

Example:

for(if(condition){var x = 0; x<number; x++}else{var x=number; x>0; x--}){
  //do something
}

Upvotes: 2

Views: 638

Answers (3)

xscott
xscott

Reputation: 2430

ActionScript has the ternary operator, so you could do something like:

for (var x = cond ? 0 : number; cond ? x < number : x > 0; cond ? x++ : x--) {
}

But this is pretty ugly. :-)

You might also need/want to put some parens around pieces of that. I'm not sure about the operator precedence.

You might also consider using a higher order function. Imagine you have:

function forward (count, func) {
    for (var x = 0; x < count; x++) {
        func(x);
    }
}

function backward (count, func) {
    for (var x = count - 1; x >= 0; x--) {
        func(x);
    }
}

Then you could do:

(condition ? forward : backward) (number, function (x) {
     // Your loop code goes here
})

Upvotes: 6

Matthew Flaschen
Matthew Flaschen

Reputation: 285077

Interesting requirement. One way to keep the for is:

var start, loop_cond, inc; 
if(condition) 
{ 
    start = 0; 
    inc = 1; 
    loop_cond = function(){return x < number}; 
} 
else 
{ 
    start = number - 1; 
    inc = -1; 
    loop_cond = function(){return x >= 0}; 
} 
for(var x = start; loop_cond(); x += inc) 
{ 
    // do something
}

We setup the start value, a function for the termination condition, and either a positive or negative increment. Then, we just call the function and use += to the do the increment or decrement.

Upvotes: 9

Josh
Josh

Reputation: 11070

You probably want a while loop instead:

var continueLooping, x;

if(condition)
{
  x = 0
  continueLooping = (x < number);
}
else
{
  x = number;
  continueLooping = (x > 0);
}

while (continueLooping)
{
  // do something
  if(condition)
  {
    x++;
    continueLooping = (x < number);
  }
  else
  {
    x--;
    continueLooping = (x > 0);
  }
}

If you really want a for loop, you should use two of them:

function doSomething()
{
  //doSomething
}

if(condition)
{
  for(var x = 0; x<number; x++)
  {
    doSomething(x);
  }
}
else
{
  for(var x=number; x>0; x--})
  {
    doSomething(x);
  }
}

Upvotes: 1

Related Questions