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

109
Vistas
If-statement executes everything but return-statement

I'm trying to understand how stacks are working through code. Now, I tried to write a simple bracket-matching program: I've wrote linked list implementation and I've used it to implement stack in JS. The idea is in iterating through all characters in string and putting open-brackets in stack. After this, if there is no matching bracket for the top-bracket, function should return false. The main problem is, that if-statement executes everything but return-statement in it.

Input: ([(a()]])

Desired output: false

function isBalanced(string) {
  let stack = new Stack();
  [...string].forEach(char => {
    let bracket
    if (char === '[' || char === '(') {
      stack.push(char)
    } else {
      if (stack.isEmpty()) {
        return false
      }

      bracket = stack.pop().data
      console.log(`PAIR: ${bracket}${char}`)
      if (!(bracket === "[" && char === "]") && !(bracket === "(" && char === ")")) {
        console.log("working")
        return false
      }
    }});

    return stack.isEmpty();
}

let string = '([(a()]])'

console.log(isBalanced(string))

I've used console.log() to check if my statement works and on which pairs does it work.

Output in console looks like this:

PAIR: (a
working
PAIR: ()
PAIR: []
PAIR: (]
working
true

As you can see, when statement is true, it's definitely work, but it doesn't call the inner return-statement (after first 'working' output, there should be no more pairs in console; just false). Where is the problem?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You could use Array#every along with the length check of the stack and return inside of the callback for every right character true.

function isBalanced(string) {
    const
        closed = { '(': ')', '[': ']' },
        stack = [];
    return [...string].every(char => {
        if (char === '[' || char === '(') {
            stack.push(char);
            return true;
        }
        if (!stack.length) return false;
        const bracket = stack.pop();
        console.log(`PAIR: ${bracket}${char}`);
        return closed[bracket] === char;
    }) && !stack.length;
}

console.log(isBalanced('(([()]))'));
console.log(isBalanced('([(a()]])'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

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