Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Is matching brackets
function isMatchingBrackets(str) {
let stack = [];
const map = {
'(': ')',
'[': ']',
'{': '}'
};
let answer = false;
for (let c of [...str]) {
if (Object.keys(map).includes(c)) {
// is opening
stack.push(c);
} else {
// if it's closing type
// check if stack is empty
if (stack.length === 0) {
// i return false because stack is empty and i want to break out of the loop
answer = false
break;
} else {
const lastOpen = stack.pop() // has to be ( { [
const match = map[lastOpen] === c;
if (match) {
// i have a match (this closing has an opening as the last item in stack
answer = true;
} else {
// i dont have a match
answer = false;
}
}
}
}
if (stack.length) {
answer = false
}
return answer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.