0

So here is my code

function balancedBrackets(string) {
  let splited = string.split("");
  let stack = [];
  splited.forEach((x)=>{
    if(x=== '('|| x === '[' || x==='{'){
      stack.push(x)
    } else if( x=== ')'|| x === ']' || x==='}'){
     if((x === ')' && stack[stack.length - 1]!='(') || (x === ']' && stack[stack.length - 1]!='[') ||  (x === '{' && stack[stack.length - 1]!='}') || (stack.lenght===0)){
      return false
     }  else {
       stack.pop();
      }
    }
    
    });
  return stack.length === 0
}

It's a function to find if the string of brackets is balanced, and it works partially but when you just imput a closing bracket as the only argument is returns true when it should be returning false as its specified in the if statemen after the else if

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40

1 Answers1

1

You cannot return from forEach. Replace it with the normal for-loop and it will work.

forEach function takes just a function to execute over an array element. It does not care for the return value of the passed function.

This would also work:

for(let item in items) {
}
Aid Hadzic
  • 578
  • 3
  • 10