Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

307
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda