将比较运算符的字符串表示形式转换为实际的比较运算符

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

我正在尝试在 JavaScript 中创建一个动态函数,我可以在其中将一个对象与另一个对象进行比较,并将比较运算符作为字符串值传递给该函数。

例如像这样的两个对象:

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

我想比较香蕉和苹果,有没有一种方法可以传递比较运算符的字符串表示形式,然后将其用作函数中的实际比较运算符?

function compare (first, second, comparator) {

    return first.id (comparator) second.id;

}

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

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

等等

当然我可以在比较器字符串上使用 switch 或 if 语句来实现,即

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

但我想知道是否有更好更有效的方法来避免需要这样的 switch/if 语句。

虽然这在某些语言中可能可行,但 JavaScript 不是其中之一。

我个人认为这是个坏主意,因为它危险地接近 eval 领土。我认为您应该将运算符列入白名单并定义它们的行为:

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