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 '&&' in expression #253

Open gkjohnson opened 3 years ago

gkjohnson commented 3 years ago

When declaring '&&' in the "binaryOps" field an error is thrown when parsing a binary '&&' expression:

import { Parser } from 'expr-eval';

const parser = new Parser();
parser.binaryOps[ '&&' ] = ( a, b ) => Boolean( a && b );
parser.evaluate( '1 && 1' );

// error!

Thanks for the awesome library!

silentmatt commented 3 years ago

Unfortunately, the binaryOps object can't be used to add new operators, only change the implementation of existing ones. It's kind of confusing because you can add to unaryOps (with the limitation that the operator needs to be a valid identifier, so no special characters). It's something that would be nice to support in the future, but isn't currently because of how the parser works.

gkjohnson commented 3 years ago

Got it -- makes sense. Reworking the parsing for unary ops sounds like a large task. As a smaller adjustment it might be nice to add support for just && as an empty / non-implemented operator so users can override the behavior considering it's frequently used as boolean AND. It could throw an error by default so people don't mistakenly use it without it being overwritten.

Thanks again!