Skip to content

Instantly share code, notes, and snippets.

@bradoyler
Last active August 29, 2015 14:05
Show Gist options
  • Save bradoyler/b98c4ed759499f2b34a0 to your computer and use it in GitHub Desktop.
Save bradoyler/b98c4ed759499f2b34a0 to your computer and use it in GitHub Desktop.
check for balanced parens
function parenthesesAreBalanced(s)
{
var parentheses = "[]{}()",
stack = [], //Parentheses stack
i, //Index in the string
c; //Character in the string
for (i = 0; c = s[i++];)
{
var bracePosition = parentheses.indexOf(c),
braceType;
//~ is truthy for any number but -1
if (!~bracePosition)
continue;
braceType = bracePosition % 2 ? 'closed' : 'open';
if (braceType === 'closed')
{
//If there's no open paren, return false OR if opening paren does not match.
if (!stack.length || parentheses.indexOf(stack.pop()) != bracePosition - 1)
return false;
}
else
{
stack.push(c);
}
}
//If anything is left on the stack <- not balanced
return !stack.length;
}
// OR, using RegEx...
function isBalanced(string) {
return !!balanced.matches({source: string, open: ['{', '(', '['], close: ['}', ')', ']'], balance: true});
}
parenthesesAreBalanced('{}([])'); // true
parenthesesAreBalanced('{{'); // false
isBalanced('{}([])'); // true
isBalanced('{{'); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment