silentmatt / expr-eval

Mathematical expression evaluator in JavaScript
http://silentmatt.com/javascript-expression-evaluator/
MIT License
1.21k stars 239 forks source link

Cannot use the AND or OR operators #245

Open Gillardo opened 3 years ago

Gillardo commented 3 years ago

Looking at the code, on line 93 of the parser.js file, you have

this.binaryOps = {
    '+': add,
    '-': sub,
    '*': mul,
    '/': div,
    '%': mod,
    '^': Math.pow,
    '||': concat,
    '==': equal,
    '!=': notEqual,
    '>': greaterThan,
    '<': lessThan,
    '>=': greaterThanEqual,
    '<=': lessThanEqual,
    and: andOperator,
    or: orOperator,
    'in': inOperator,
    '=': setVar,
    '[': arrayIndex
  };

Why is the and and or methods not strings? I am trying to use AND or OR for an expression, but it never seems to work, here is an example of a simple formula to execute

[A]==1 AND [B]==2 or [A]==1 OR [B]==2

But doing this returns an exception, even if i try to use && or || instead of the words.

To use AND and OR, I have wrote my own IIF function which allows you to pass in an expression and a return value with an ELSE value as well if the expression isnt true, for example IIF([A]==1 AND [B]==2, 1, 0) this checks if [A] equals 1 and [B] equals 2, if so, should return value of 1, else returns a value of 0.

I thought i could override it like i do with the + operator, but that doesnt seem to work. For + all i do is this

parser[ 'binaryOps' ][ '+' ] = (a, b) => {
    if (a == null || b == null) {
        return null;
    }

    return +((a + b).toFixed(2));
};

I would of thought that maybe AND or OR could be achived with something like

parser[ 'binaryOps' ][ 'AND' ] = (a, b) => {
    return a && b;
};

Can you let me know if its possible to use AND and OR in this way to test multiple expressions?