Figa17 Figa17 - 2 months ago 8
Node.js Question

validate math equation with empty brackets

I need to validate an equation, actually i have bracket validation but that don't validate if the brackets are empty only if brackets are balanced.

For example

2 + 5 + (3 * {1 – 2}) = 4
return true, but
1 + ()
also return true and i need to return false.

This is my code


function mathFormulaValidator(string) {
"use strict";

let formulaSP = string.replace(/ /g, ""),
arr = [],
valid = true;

for (let i = 0; i < formulaSP.length; i++) {
let char = formulaSP.charAt(i);
switch (char) {
case '(':
arr.push(1);
break;
case ')':
if (arr.pop() != 1) {
valid = false;
}
break;
case '[':
arr.push(2);
break;
case ']':
if (arr.pop() != 2) {
valid = false;
}
break;
case '{':
arr.push(3);
break;
case '}':
if (arr.pop() != 3) {
valid = false;
}
break;
default:
console.error(char);
break;
}
}
return valid;
}


How can validate if the brackets are empty?? any ideas?

Answer

Use this:

string.match(/\(\)|{}|\[\]/) == null

This will return true if there are no empty (), {} or []

If there are any of those present, it will return false.

For example:

"[]".match(/\(\)|{}|\[\]/) == null
false

"{(}".match(/\(\)|{}|\[\]/) == null
true

"2 + 5 + (3 * {1 – 2}) = 4".match(/\(\)|{}|\[\]/) == null
true

"1 + ()".match(/\(\)|{}|\[\]/) == null
false
Comments