expr-eval
expr-eval copied to clipboard
Option for Parser to evaluate expression with missing variables as undefined
Currently if you try to evaluate an expression without providing a value for all the variables, the library throws an exception.
In my situation I wanted to have smallest conditional expressions like a and b=='2'
meaning that if a
is not undefined
and b
is '2'
.
The ways that I found to do this is to create a function out of expression with toJsFunction
and pass undefined
variables.
I'm suggesting to add an option to Parser options like evaluateOnMissingVariables
so on evaluating expression, all missing variables get undefined
value instead of throwing an exception.
The default of this option can be false
so this can be backward compatible.
Looking a little bit inside the code, it seems that lines 29 to 32 in expression.js can be a good place for this logic.
I did this const { Parser, Expression } = require('expr-eval');
Expression.prototype.safeEvaluvate = function (values, defaultValue) {
try {
return this.evaluate(values);
} catch (e) {
console.error(Exception in safeEvaluvate: ${e.message}
);
return defaultValue;
}
};
I'm looking for not undefinedVariable to return true... I don't see anyway to do this atm.