Skip to content

Instantly share code, notes, and snippets.

@kolber
Created July 1, 2010 02:42
Show Gist options
  • Save kolber/459490 to your computer and use it in GitHub Desktop.
Save kolber/459490 to your computer and use it in GitHub Desktop.
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