I have a valid mathematical expression that just needs to be ended with some closing parentheses for eval() to work. For this, I can find the unclosed parentheses in the expression and append closing parentheses until the unclosed parentheses match with the closing parentheses.
This is what I have done:
let expression = `3 * 1 * (4 - 1 - (5 * 9 * (2 - 6 / 5 + (4 - 1 - (5 * 9 * (2 - 6 / 5 -
(4 - 1 - (5 * 9 * (2 - 6 / 5 + (4 - 1 - (5 * 9 * (2 - 6 / 5`;
const openingParenthesisCount = (expression.match(/[(]/g) || []).length;
const closingParenthesisCount = (expression.match(/[)]/g) || []).length;
let unclosedParenthesisCount =
openingParenthesisCount - closingParenthesisCount;
try {
console.log(eval(expression));
} catch (error) {
// Append closing parentheses until all the parentheses are closed
while (unclosedParenthesisCount) {
expression += ")";
unclosedParenthesisCount--;
}
}
// Valid expression
console.log(eval(expression));
I have used a test expression for this and it works, but if the expression is longer, it may take some time (but eventually will show the result).
Is there an easier/ faster method to achieve this?
I suggest using built-in functionality of String#repeat() and use single loop instead of RegExp.
const openedCount = Array.from(expression).reduce(
(opened, curChar)=> {
if (curChar === '(') opened++
else if (curChar === ')') opened--
return opened
},
0
)
expression += ')'.repeat(openedCount)