DEV Community

Cover image for Homework: Brackets Check in JS
decker
decker

Posted on

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 (1)

Collapse
 
johnson_cedrick profile image
Johnson cedrick

Thanks for sharing your information. We have some plans to complete the homework. The main moto is to revise through homework Seeking assistance to 'write my thesis' can streamline the daunting process of academic research and writing, ensuring clarity and scholarly rigor read more academized.com/write-my-thesis Professional guidance helps navigate complexities, ensuring a well-structured and insightful thesis that meets academic standards. It's a strategic investment in academic success and a testament to rigorous scholarship