Search code examples
javascriptcomparison-operators

Convert a string representation of a comparison operator to an actual comparison operator


I'm trying to create a dynamic function in JavaScript where I can compare one object to another, passing in the comparison operator as a string value to the function.

E.g two objects like this:

{value: 1, name: "banana"}
{value: 2, name: "apples"}

I want to compare banana to apple, is there a way I can pass a string representation of a comparison operator and then use it as an actual comparison operator in a function?

function compare (first, second, comparator) {

    return first.id (comparator) second.id;

}

e.g compare(apple,banana,"<=");
//return true

compare(apple,banana,"===");
//return false

etc

Granted I could implement with a switch or if statement on the comparator string i.e.

 if (comparator === "<=")
    return first.id <= second.id
    if (comparator === "===")
    return first.id === second.id

but I wonder if there is any better more efficient way to do it that avoids the need for such a switch/if statement.


Solution

  • While this might be possible in some languages, JavaScript is not one of them.

    Personally I think it's a bad idea, as it comes dangerously close to eval territory. I think you should whitelist the operators and define their behaviour:

    switch(comparator) {
        case "<=": return first.id <= second.id;
        case "===": return first.id === second.id;
        // ...
        // you can have synonyms:
        case ">=":
        case "gte": return first.id >= second.id;
        // or even nonexistant operators
        case "<=>": // spaceship!
            if( first.id === second.id) return 0;
            if( first.id < second.id) return -1;
            return 1;
        // and a catch-all:
        default:
            throw new Error("Invalid operator.");
    }