dev-resources.site
for different kinds of informations.
Homework: Brackets Check in JS
Published at
12/6/2022
Categories
javascript
homework
student
programming
Author
decker67
Author
8 person written this
decker67
open
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?
homework Article's
15 articles in total
5 Reasons Why Homework Should Be Banned?
read article
Simplify Your Homework and Study Time Efficiently
read article
How to Write an Assignment and Secure A+ Marks
read article
The Ultimate Guide to Help You Help with Physics Homework Free
read article
One-to-One Academic Help: Unlocking Your Full Potential
read article
WHY DO STUDENTS HAVE DIFFICULTIES WITH PYTHON PROGRAMMING HOMEWORK?
read article
hw 7 questions on articles
read article
Should I use ChatGPT for school assignments?
read article
Homework: Brackets Check in JS
currently reading
Need Statistics Homework Help
read article
Is Homework Illegal?
read article
Supporting Children's Learning - A Guide For Parents
read article
7 Strategies to Make Homework Go More Smoothly
read article
need help with c++ calculator
read article
How Should One Explain The Academic/Employment Gaps On A Resume?
read article
Featured ones: