Homework: Brackets Check in JS
decker
Posted on December 6, 2022
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
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
What do you think? Is there a more elegant version to do it?
💖 💪 🙅 🚩
decker
Posted on December 6, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.