Skip to content

Instantly share code, notes, and snippets.

@PunkSage
Last active July 7, 2016 12:17
Show Gist options
  • Save PunkSage/5edcdf2ceda6300e07c02c1164d606eb to your computer and use it in GitHub Desktop.
Save PunkSage/5edcdf2ceda6300e07c02c1164d606eb to your computer and use it in GitHub Desktop.
/* Verify if a given string has a proper parenthesis setup */
function verify(str) {
var array = str.split('');
var stack = [];
var left = ['{','[','('];
var right = ['}',']',')'];
var opposite = {
')':'(',
'}':'{',
']':'[',
}
while (array.length > 0) {
var x = array.shift();
if (right.indexOf(x) > -1) {
if (stack.pop() !== opposite[x]) return false;
} else {
stack.push(x);
}
}
return (stack.length === 0);
}
console.log('empty',verify(''));
console.log('{[]{}}',verify('{[]{}}'));
console.log('(}{)',verify('(}{)'));
console.log('}{',verify('}{'));
console.log('{}',verify('{}'));
console.log('})]',verify('})]'));
console.log('{(}',verify('{(}'));
console.log('({})',verify('({})'));
console.log('([)]',verify('([)]'));
console.log('{{}}',verify('{{}}'));
console.log('()',verify('()'));
console.log('(()',verify('(()'));
console.log(')(',verify(')('));
console.log('(())()()',verify('(())()()'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment