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

256
Visualizações
How to extrude and execute the contents between brackets?

I need to execute an expression according to Order of Operations, and I can't figure out how to resolve the side-by-side brackets.

I am receiving an expression as a string -> "(add (multiply 4 5) (add 13 1))"

I can't figure out how to resolve this side by side case.

How I have it working for a case where everything is nested by grabbing the innermost brackets and then solving the next like this:

// Find innermost equasion
const findInnerEq = (str) =>
str.substring(str.lastIndexOf("(") + 1, str.lastIndexOf(")"));


// Find Brackets RegEx
const brakets = /(?<=\().*(?=\))/g;

// Changing RegEx function
const changeRE = (str) =>
  str.slice(str.lastIndexOf("(") + 1, str.indexOf(")"));

// Return calculation
const calculate = (str) => {
  let exp = findInnerEq(str).toLowerCase().split(" ");
  let calc = exp
    .slice(1)
    .map((element) => parseInt(element))

  switch (exp[0]) {
    case "add":
      if (calc.length > 2){
        return calc.reduce((acc, cur) => acc + cur, 0);
      }
      return calc[0] + calc[1]  
      break;
    case "multiply":
      return calc.reduce((acc, cur) => acc * cur, 1);
      break;
    default:
      console.log("Please enter valid expression");
      process.exit();
  }
};


// Recursive function
const calculator = (str) => {
  let curString;
  if (str.match(brakets)) {
    curString = str;
    let changingReg = `\(${changeRE(curString)}\)`;
    curString = curString.replace(changingReg, calculate(curString));
    return calculator(curString);
  } else {
    return str;
  }
};

console.log(calculator("(add 2 (multiply 2 2))"));
console.log(calculator("(add (multiply 2 2) (add 2 2)"));

How can I deal with the side-by-side brackets?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Well, it looks like a classic problem from CS, and you are approaching it wrong.

What you should do instead, is use stacks, pushing items to them until you meet ')', which will tell you to execute the action on the stack collected so far.

Here is one of explanations https://orkhanhuseyn.medium.com/what-are-stack-based-calculators-cf2dbe249264

about 4 years ago · Juan Pablo Isaza Relatório

0

try this:

let arr = str.split("(").join("|:|:|:|").split(")").join("|:|:|:|").split("|:|:|:|")
//arr is now an array that has been split at both ( and )
// the middle value: arr[arr.length/2]
//evaluate it, and then combine it with arr[arr.length/2+1] and arr[arr.length/2-1]
//continue the cycle until your whole expression is evaluated
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