Skip to content

Instantly share code, notes, and snippets.

@zhaocnus
Last active May 1, 2024 21:14
Show Gist options
  • Select an option

  • Save zhaocnus/ec9a962f5d24c9cc6696524669691879 to your computer and use it in GitHub Desktop.

Select an option

Save zhaocnus/ec9a962f5d24c9cc6696524669691879 to your computer and use it in GitHub Desktop.
/**
* braces/brackets/parentheses validator
*/
function check(str) {
const closers = {
')' : '(',
'}' : '{',
']' : '['
};
const openers = {
'(' : true,
'{' : true,
'[' : true
};
const all = [];
for (let i = 0; i < str.length; i++) {
let char = str.charAt(i);
if (closers[char]) {
if (all.length === 0) return false;
let opener = all[all.length - 1];
if (closers[char] === opener) {
all.pop();
}
} else if (openers[char]) {
all.push(char);
}
}
// Is valid if no outstanding opener
return all.length === 0;
}
// test cases
console.log(check(''));
console.log(check('{ s[ dfg]fdgdfg ( ) }'));
console.log(check('{ [ ( ] ) }'));
console.log(check('{ [ }'));
console.log(check('}'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment