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

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

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 Denunciar

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