DEV Community

Cover image for Homework: Brackets Check in JS
decker
decker

Posted on

3 2

Homework: Brackets Check in JS

I recentliy saw a homework for students in which you should write a function that gives true if a string with brackets of different types closes brackets accordingly otherwise false.

My first solution not using a stack was this:

const openBrackets = '([{'
const closingBrackets = ')]}'

function checkBrackets (string) {
  let bracketsStack = ''
  for (let i = 0; i < string.length; i++) {
    const char = string[i]
    if (openBrackets.includes(char)) {
      bracketsStack += char
    } else if (closingBrackets.includes(char)) {
      const lastBracket = bracketsStack[bracketsStack.length - 1]
      if ((lastBracket === '(' && char !== ')') ||
          (lastBracket === '{' && char !== '}') ||
          (lastBracket === '[' && char !== ']')) {
        return false
      }
      bracketsStack = bracketsStack.substring(0, bracketsStack.length - 1)
    }
  }
  return true
}

console.log(checkBrackets('()()')) // true
console.log(checkBrackets('([])')) // true
console.log(checkBrackets('([)]')) // false
Enter fullscreen mode Exit fullscreen mode

But it looks a bit ugly using the big if and I created a second one using a map, to make it shorter and easier, I would think.

const brackets = {
  '(': ')',
  '{': '}',
  '[': ']',
}
const openingBrackets = Object.keys(brackets)
const closingBrackets = Object.values(brackets)

function checkBrackets (string) {
  const bracketsStack = []
  charIterator = string[Symbol.iterator]()
  let char
  while (char = charIterator.next().value) {
    if (openingBrackets.includes(char)) {
      bracketsStack.push(char)
    } else if (closingBrackets.includes(char)) {
      if (brackets[bracketsStack.pop()] !== char) {
        return false
      }
    } 
  }
  return true
} 


console.log(checkBrackets('()()')) // true
console.log(checkBrackets('([])')) // true
console.log(checkBrackets('([)]')) // false
Enter fullscreen mode Exit fullscreen mode

What do you think? Is there a more elegant version to do it?

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Agent.ai Challenge image

Congrats to the Agent.ai Challenge Winners 🏆

The wait is over! We are excited to announce the winners of the Agent.ai Challenge.

From meal planners to fundraising automators to comprehensive stock analysts, our team of judges hung out with a lot of agents and had a lot to deliberate over. There were so many creative and innovative submissions, it is always so difficult to select our winners.

Read more →

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay