Js - 使用运算符作为字符串来评估数学表达式的替代方法

jy9*_*y95 5 javascript eval node.js typescript

我有一个库,它具有基于某些字段过滤对象的功能(每个字段都有特定类型的类型 - 有关https://github.com/jy95/mediaScan/wiki 的更多信息)

最大的问题是处理来自多个来源的数字属性

// to handle number operations
export interface NumberExpressionObject {
    operator: "==" | ">" | "<" | ">=" | "<=";
    number: number;
}

// additional Properties
export interface AdditionalProperties {
    type: AdditionalPropertiesType;
    name: string;
    value: boolean | string | string[] | number | NumberSearchSyntax;
}
Run Code Online (Sandbox Code Playgroud)

例如 :

expect((libInstance.filterTvSeries({
            additionalProperties: [
                {type: "number", name: "whateverFieldThatDoesn'tExist", value: "<50"},
                {type: "number", name: "AnotherField", value: undefined},
                {type: "number", name: "AnotherField2", value: "<=25"},
                {type: "number", name: "AnotherField3", value: ">25"},
                {type: "number", name: "AnotherField4", value: "==25"},
            ],
            season: ">=4",
        }))).toEqual(
            new Map(),
        );
Run Code Online (Sandbox Code Playgroud)

每个必须首先对应以下正则表达式:

const validExpression = /^(==|>|<|>=|<=)(\d+)$/;
Run Code Online (Sandbox Code Playgroud)

然后将通过此函数进行评估:

function resolveExpression(property: string,
                           expressionObject: MediaScanTypes.NumberExpressionObject,
                           object: MediaScanTypes.TPN | MediaScanTypes.TPN_Extended): boolean {
    return eval(`${object[property]}${expressionObject.operator}${expressionObject.number}`);
}
Run Code Online (Sandbox Code Playgroud)

我想知道有什么更简洁的方法可以做到这一点......请避免像 switch case 这样的简单答案:我测试过它,但在我的测试中它仍然比 eval 慢......

函数构造函数对我来说与 eval ..

我读过的以前的帖子:
将字符串作为 JavaScript 中的数学表达式求值
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
https://developer.mozilla.org/en -US/docs/Web/JavaScript/Reference/Global_Objects/Function
...

aar*_*iao 2

  1. 为运营商实现功能

    ops = { '>': (a, b) => a > b, '>=': (a, b) => a >= b };

    ops[表达式对象. 运算符](对象[属性], 表达式对象. 编号)

  2. 如果表达式始终如预期有效。那么以下应该更快,因为没有解析。

    评估(${object[property]}${expression}