expr-eval icon indicating copy to clipboard operation
expr-eval copied to clipboard

Option for Parser to evaluate expression with missing variables as undefined

Open SHND opened this issue 4 years ago • 3 comments

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 avatar Oct 18 '19 00:10 SHND

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.

SHND avatar Oct 18 '19 01:10 SHND

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

deepankumaresan avatar Jun 19 '20 09:06 deepankumaresan

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

Charuru avatar Jan 26 '22 02:01 Charuru