silentmatt / expr-eval

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

Option for Parser to evaluate expression with missing variables as undefined #216

Open SHND opened 4 years ago

SHND commented 4 years ago

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.

SHND commented 4 years ago

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.

deepankumaresan commented 4 years ago

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; } };

Charuru commented 2 years ago

I'm looking for not undefinedVariable to return true... I don't see anyway to do this atm.