在循环中使用变量作为大于/小于运算符

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

最近,我一直在摆弄一些紧凑的代码,我正在尝试让一个非常奇怪的 for 循环尽可能小。

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");
//}

我知道我可以让循环像 if / else 语句一样工作,但我正在寻找一种更小的方法来做到这一点,因为这会使代码大两倍(更长 "for loops").

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

是的,有什么办法可以做到这一点吗?还是我坚持只用 1 个不同的字符制作两个不同的循环?提前致谢

您可以使用函数而不是字符串,因为可以在不使用 eval 的情况下调用函数,这是不可取的。

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);