evaluate static method
dynamic
evaluate(})
Implementation
static dynamic evaluate(String? expression, {Map<String?, dynamic>? variables, Map<String?, dynamic>? altFunctions})
{
if (expression == null) return null;
var result;
var _expression = expression;
var _parsed;
var i = 0;
var _variables = Map<String, dynamic>();
var _functions = Map<String?, dynamic>();
try
{
// setup variable substitutions
if (variables != null)
variables.forEach((key,value)
{
i++;
var _key = "___V$i";
_variables[_key] = _isNumeric(value) ? _toNum(value) : _isBool(value) ? _toBool(value) : value;
_expression = _expression.replaceAll(key!, _key);
});
// add variables
_functions.addAll(_variables);
// add functions
_functions.addAll(functions);
// add alternate functions that dont clash
altFunctions?.forEach((key, value) => _functions.containsKey(key) ? null : _functions[key] = value);
// parse the expression
_parsed = Expression.tryParse(_expression);
// failed parse?
if (_parsed == null) throw(Exception('Failed to parse $_expression'));
// required to replace quoted string observables
_parsed = replaceInLiterals(_parsed, _variables);
// evaluate the expression
result = evaluator.eval(_parsed, _functions);
}
catch(e)
{
String? msg;
if (variables != null) variables.forEach((key, value) => msg = (msg ?? "") + (msg == null ? "" : ", ") + "$key=${value.toString()}");
Log().debug("eval($expression) [$msg] failed. Error is $e");
result = null;
}
return result;
}