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

305
Views
¿Cómo corregir la expresión para eval () para paréntesis al final?

Tengo una expresión matemática válida que solo necesita terminar con algunos paréntesis de cierre para que eval() funcione. Para esto, puedo encontrar los paréntesis sin cerrar en la expresión y agregar paréntesis de cierre hasta que los paréntesis sin cerrar coincidan con los paréntesis de cierre.

Esto es lo que he hecho:

 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));

He usado una expresión de prueba para esto y funciona, pero si la expresión es más larga, puede llevar algo de tiempo (pero finalmente mostrará el resultado).

¿Existe un método más fácil/rápido para lograr esto?

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

0

Sugiero usar la funcionalidad incorporada de String#repeat() y usar un solo bucle en lugar de 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!