Milad
Milad

Reputation: 28592

convert a string containing boolean values to a boolean

If I have this ;

  var a = "(true && false) && true && false"

And if I want to evaluate this string , what are the options ?

If I say, this code will be generated in the browser but there will be absolutely no user input in it , would it be safe to use eval ?

If not, what is the most performant way of parsing it ?

EDIt :

By the way, the string is dynamic , so I can't gaurantee that it's always like above , so it could be :

  var a = "(true && false) || (true && (true && false)) && true && false"

FIY : I know I can use eval, all I'm asking is, why I shouldn't use eval, or is there any other options?

EDIT : the original problem :

 var a = function(){ return false} // all of them always return a boolean
 var b = function(){ return true}
 var c = function(){ return true}
 var d = function(){ return false}

 var conditions = "(a && b) && c && d"

I can't change the above code , I need to parse it, I need the condition to be evaluated ;

Upvotes: 3

Views: 171

Answers (3)

Arg0n
Arg0n

Reputation: 8423

An attempt at actually writing a parser for boolean strings:

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

var exp1 = "(true && true || false) && (true || (false && true))";
var exp2 = "(true && false) && true && false";
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;
}

Usage would then simply be parseBoolStr('true && false'); //false

Upvotes: 0

Arg0n
Arg0n

Reputation: 8423

I was thinking maybe you can atleast verify that the string contains what you think it should contain, before running eval on it, using the RegExp /(?:(?:true)|(?:false)|(?:&&)|(?:\|\|)|[()\s])/g:

var validExp = "(true && false && true) || (true && (true && false)) && true";
var evilExp = "(true && false && true) || (true && (true && false)) && true function() { console.log('do evil stuff'); }";

console.log(evalBoolStr(validExp)); //false
console.log(evalBoolStr(evilExp)); //Invalid input

function evalBoolStr(str) {
  if(str.match(/(?:(?:true)|(?:false)|(?:&&)|(?:\|\|)|[()\s])/g).join('') === str) {
    return eval(str);
  }
  return 'Invalid input';
}

Upvotes: 0

user7633250
user7633250

Reputation:

function ExecuteJavascriptString() {
    var n = 0;
    var s = "(true || false) || (true || (true || false)) && true";
    var ifstate = " if (" + s + ") { console.log('done'); } ";
    setTimeout(ifstate, 1);
}

ExecuteJavascriptString()

Upvotes: 2

Related Questions