Last active
August 29, 2015 14:05
-
-
Save bradoyler/b98c4ed759499f2b34a0 to your computer and use it in GitHub Desktop.
check for balanced parens
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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