Created
July 1, 2010 02:42
-
-
Save kolber/459490 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
var balanced_parens = function(str) { | |
var stack = arguments[1] || []; | |
if (str.charAt(0) == '') { | |
return stack.length === 0; | |
} | |
else if (str.charAt(0) == '{') { | |
stack.push(str); | |
} | |
else if (str.charAt(0) == '}') { | |
if (!stack.pop()) { | |
return false; | |
} | |
} | |
return arguments.callee.call(this, str.substring(1), stack); | |
} | |
/* | |
Test it | |
*/ | |
var test_strings = [ | |
"{ level 1 { { level 3 } level 2 { level 3 } } }", | |
"{ level 1 { { { level 3 } level 2 { level 3 } } }", | |
"{ level 1 { { level 3 } level 2 { level 3 } } } }" | |
]; | |
for (var i = test_strings.length - 1; i >= 0; i--) { | |
var str = test_strings[i]; | |
console.log('"'+str+'" is '+(balanced_parens(str) ? 'well' : 'not well')+' balanced.'); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment