Search code examples
javascriptstringloopscomparison

Using variables as greater than / less than operators in a loop


Lately, I've been messing around with some compact code, and i'm trying to get a quite weird for loop as small as possible.

function test (start, comparison, end, increment) {
    for (x = star; x comparison end; x += increment) {
        console.log("e");
    }
}
test(1, "<", 3, 1);

//Expected theoretically
// for (x = 1; x < 3; x += 1) {
//  console.log("e");
//}

I know I can get the loop to work with like for example an if / else statement, but I am looking for a smaller way to do this, since this makes the code twice as big (for longer "for loops").

function test (start, value, end, increment) {
  if (value > 0) {
    //Loop 1
  } else {
    //Loop 2
  }
}

So yea, is there any way to do this? or am I stuck with making two different loops with just 1 different character? Thanks in advance


Solution

  • You could take a function instead of a string, because the function can becalled without using eval, which is not advisable.

    function test (start, comparison, end, increment) {
        for (var x = start; comparison(x, end); x += increment) {
            console.log(x);
        }
    }
    
    const isSmaller = (a, b) => a < b;
    
    test(1, isSmaller, 3, 1);