Skip to content

Instantly share code, notes, and snippets.

@iuliaL
Created March 2, 2019 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iuliaL/8f0589418ac1e4c4d7cd48d2cd3202d1 to your computer and use it in GitHub Desktop.
Save iuliaL/8f0589418ac1e4c4d7cd48d2cd3202d1 to your computer and use it in GitHub Desktop.
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