Home > Blockchain >  Parsing & Checking Condition String in Javascript
Parsing & Checking Condition String in Javascript

Time:04-21

I have string that have variable conditions in it, like this:

(@IS_VERIFIED = 'True' OR @CONFIRMATION_NEEDED != 'True') AND @REQUEST_LIMIT != '0'

This is just an example and there are unknown number of variables & cases.

  1. Every variable starts with @
  2. There are ORs and ANDs with sometimes parenthesis
  3. Values are always in quotation marks like 'xyz', so all can be considered strings.
  4. Conditions are always checked with either = or !=

I also have a javascript map which holds all the variables like:

const vars = {
 IS_VERIFIED: 'True',
 CONFIRMATION_NEEDED: 'True',
 REQUEST_LIMIT: '2'
}

What I need to do is parse the condition string and check the values using the map above to reach a final result, true or false. I came up with few ideas but they were all too complicated. Is there any known, easy method for this or do I have to create something from scratch?

Any help is appreciated, thanks.

Edit: After achieving this, next goal for me will be showing which variables break the condition, somehow.

CodePudding user response:

Caution: eval solution ahead, be very careful while using this!

Simply modify the string to be a valid JS expression and then use eval.

const vars = {
  IS_VERIFIED: "True",
  CONFIRMATION_NEEDED: "True",
  REQUEST_LIMIT: "2",
};

const str = `(@IS_VERIFIED = 'True' OR @CONFIRMATION_NEEDED != 'True') AND @REQUEST_LIMIT != '0'`;

const evalStr = str
  .replaceAll("@", "vars.")
  .replaceAll("OR", "||")
  .replaceAll("AND", "&&")
  .replaceAll("!=", "!")
  .replaceAll("=", "===")
  .replaceAll("!", "!==");

const res = eval(evalStr);
console.log(res);

CodePudding user response:

Here is a snippet using RegExp:

let test = "@XYZ='True' AND @ABC='False'";

const regexp = /(@\w )|(\'\w \')/g;

const regexpResult = [...test.match(regexp)]
// Returns something like this:
// ["@XYZ", "'True'", "@ABC", "'False'"]

const vars = {};

for (let i = 0; i < regexpResult.length; i  = 2) // We will be using two consecutive values at a time
{
  let keyName = regexpResult[i].replace("@", "");
  let keyValue = regexpResult[i 1].replaceAll("'", "");
  
  vars[keyName] = keyValue;
}

// OUTPUT of "vars":
// {
//   XYZ: "True",
//   ABC: "False"
// }

I hope this gives you an idea about how to solve your problem.

  • Related