jQuery if statement with variable mathematical operator [duplicate]

You could define a lot of binary functions:

var operators = {
    "==": function(a,b){return a==b;},
    "<=": function(a,b){return a<=b;},
    ">=": function(a,b){return a>=b;},
    "<": function(a,b){return a<b;},
    ">": function(a,b){return a>b;},
    …
};

var one = "4",
    two = "6",
    op = "==";
if (op in operators && operators[op](+one, +two)) {
    //do something
}

If you don’t want to generate such a large object and have no complex functions, you also might be able to generate them on-the-fly (using a bit of eval magic):

var validOps = /^([!=<>]=|<|>)$/,
    operators = {};
function check(op, x, y) {
    if (arguments.length > 1)
        return check(op)(x, y);
    if (op in operators)
        return operators[op];
    if (validOps.test(op))
        return operators[op] = new Function("a","b","return a "+op+" b;");
    return function(a, b){return false;};
}

if (check("==", 4, 6)) {
    // do something
}

Leave a Comment