javascriptlogical-operatorsboolean-expressionexpression-evaluation

how to evaluate a string in the format (AND, true, false, (OR, true, false, false, (AND, false, true))) in Javascript?


I have string in the format (AND, true, false, (OR, true, false, false, (AND, false, true))) for example, Is there a way in JavaScript by which we can evaluate this string to a boolean value?

expression 1: (AND, true, false) => false

expression 2: (AND, true, (OR, false, true)) will evaluate to => (AND, true, true) => true

like this we can have an expression with nested conditions.

Any solution for solving this one will be a huge help. Thanks in advance


Solution

  • One option is to use a regular expression to match either an (OR ... or (AND sequence which doesn't contain any nested parentheses, and replace it with the appropriate resolve value. Do this recursively until the string has only one item in it:

    const parse = (input) => {
      while (input.includes(' ')) {
        input = input.replace(
          /\((AND|OR)([^()]+)\)/g,
          (_, type, restOfBlock) => {
            // Words will become an array of the words present here, eg ['true', 'false']
            const words = restOfBlock.match(/\w+/g);
            if (type === 'OR') return words.includes('true');
            return !words.includes('false');
          }
        );
      }
      return input === 'true';
    };
    
    console.log(parse(`(AND, true, false, (OR, true, false, false, (AND, false, true)))`)); // expression 0
    console.log(parse(`(AND, true, false)`)); // expression 1
    console.log(parse(`(AND, true, (OR, false, true))`)); // expression 2