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?

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more