Created
July 11, 2018 07:41
-
-
Save swapnilshrikhande/0aaee6504e2f6e4af2ff7af2597c0073 to your computer and use it in GitHub Desktop.
Parse Javascript Boolean Expression Inside String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var exp1 = "(true && true || false) && (true || (false && true))"; | |
var exp2 = "((true && true) || false && !true)"; | |
var exp3 = "(true && !false) && true && !false"; | |
var exp4 = "(a && b) && c && d"; | |
console.log(exp1 + ' = ' + parseBoolStr(exp1)); | |
console.log(exp2 + ' = ' + parseBoolStr(exp2)); | |
console.log(exp3 + ' = ' + parseBoolStr(exp3)); | |
console.log(exp4 + ' = ' + parseBoolStr(exp4)); | |
function parseBoolStr(str) { | |
var expressions = {}; | |
var expressionRegex = new RegExp("\\((?:(?:!*true)|(?:!*false)|(?:&&)|(?:\\|\\|)|\\s|(?:!*\\w+))+\\)"); | |
var expressionIndex = 0; | |
str = str.trim(); | |
while (str.match(expressionRegex)) { | |
var match = str.match(expressionRegex)[0]; | |
var expression = 'boolExpr' + expressionIndex; | |
str = str.replace(match, expression); | |
match = match.replace('(', '').replace(')', ''); | |
expressions[expression] = match; | |
expressionIndex++; | |
} | |
return evalBoolStr(str, expressions); | |
} | |
function evalBoolStr(str, expressions) { | |
var conditions = str.split(' '); | |
if (conditions.length > 0) { | |
var validity = toBoolean(conditions[0], expressions); | |
for (var i = 1; i + 1 < conditions.length; i += 2) { | |
var comparer = conditions[i]; | |
var value = toBoolean(conditions[i + 1], expressions); | |
switch (comparer) { | |
case '&&': | |
validity = validity && value; | |
break; | |
case '||': | |
validity = validity || value; | |
break; | |
} | |
} | |
return validity; | |
} | |
return 'Invalid input'; | |
} | |
function toBoolean(str, expressions) { | |
var inversed = 0; | |
while (str.indexOf('!') === 0) { | |
str = str.replace('!', ''); | |
inversed++; | |
} | |
var validity; | |
if (str.indexOf('boolExpr') === 0) { | |
validity = evalBoolStr(expressions[str], expressions); | |
} else if (str == 'true' || str == 'false') { | |
validity = str == 'true'; | |
} else { | |
validity = window[str](); | |
} | |
for (var i = 0; i < inversed; i++) { | |
validity = !validity; | |
} | |
return validity; | |
} | |
function a() { | |
return false; | |
} | |
function b() { | |
return true; | |
} | |
function c() { | |
return true; | |
} | |
function d() { | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Credits : https://stackoverflow.com/questions/34118860/evaluate-boolean-expression-in-a-string-in-javascript-without-eval?answertab=active