'javascript conditional expression parser
I am working in JavaScript. I want to parse and evaluate conditional expression. ex:
var param1=1;
var param2=2;
var param3=3;
var expression="(param1==param2)||(param3<param1)";
I want to write a function which will accept 'expression' as a input and parse the expression as well as evaluate expression and return evaluated result.
Please let me know for any suggestions.
Thanks in advance.
Solution 1:[1]
Here is the evil one: eval();
var param1=1;
var param2=2;
var param3=3;
var expression=eval("(param1==param2)||(param3<param1)");
Then your function comes,
function myEvaluator(s) {
return eval(s);
}
You must have variables in expression public.
Solution 2:[2]
This is a really old question and I am surprised that no libraries came out since to help with this.
Out of necessity, I built a library called angel-eval that does exactly that. It parses a string expression and evaluates with a context object. It uses a parser generator called Nearley under the hood and does not use eval
or new Function(…)
.
To use, install: npm i angel-eval
const { evaluate } = require("angel-eval");
evaluate("(param1===param2)||(param3<param1)", { param1: 1, param2: 2, param3: 3 });
angel-eval
does not support ==
or !=
so you need to use ===
and !==
.
Here is a sandbox:
Solution 3:[3]
There are a few expression parsers out there, but I would like to suggest mine. It's called swan-js and it doesn't use eval or new Function.
Installation:
npm install @onlabsorg/swan-js
Usage (it works both in NodeJS and in the browser):
const swan = require('@onlabsorg/swan-js');
const evaluate = swan.parse("param1 == param2 | param3 < param1");
const context = swan.createContext({param1:1, param2:2, param3:3});
const value = await evaluate(context); // false
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | Marcello Del Buono |