Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

306
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda