Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

308
Views
How to fix expression for eval() for trailing parenthesis at the end?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!