Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable for loop

Tags:

javascript

If reverse == true I want to run one kind of loop, else I want to run another one.

Currently, here is an example of my code:

if (reverse) {
    for (var i = 0; i < length; i++) {
        ...
    }
} else {
    for (var i = length; i >= 0; i--) {
        ...
    }
}

The code inside is really big, and is quite the same. I could use a function, but this function would have so many params that is not a good choice.

So I've tried to do something like that:

var loopStart1 = startPageIndex;
if (!reverse) {
    condition1 = function(i) {
         return i < length;
    }
    increment1 = function(i) {
         return ++i;
    }
} else {
    condition1 = function(i) {
        return i >= 0;
    }
    increment1 = function(i) {
        return i--;
    }
}
mainLoop: for (var i = loopStart1; condition1(i); increment1(i)) {

But now I have an infinite loop.

Any idea on how to solve this issue?

like image 451
Vico Avatar asked Mar 02 '26 08:03

Vico


1 Answers

Why not do it inline?! ;)

var start = startPageIndex;
for (var i = start; (reverse && i >= 0) || (!reverse && i < length); reverse ? --i : ++i) { }
like image 135
eisbehr Avatar answered Mar 03 '26 21:03

eisbehr