Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active January 18, 2020 02:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfkaye/cf3315d3824da9a53bfd36252bc3e8f2 to your computer and use it in GitHub Desktop.
Save dfkaye/cf3315d3824da9a53bfd36252bc3e8f2 to your computer and use it in GitHub Desktop.
test for balanced braces, parentheses, brackets
// 10 Jan 2020
// beautiful's interview question
// better solution than https://gist.github.com/dfkaye/2e87303396fdd0402e01062594d4e89c from Consensus
function balanced(string) {
var p = string.length && string.length % 2 === 0;
if (!p) {
return false;
}
var re = /(\{\})|(\(\))|(\[\])/;
var m;
while (m = string.match(re)) {
string = string.replace(m[0], '');
}
return string.length === 0;
}
/* test it out */
var tests = [
"{}",
"({})",
"[({})]",
"{(})",
"{{}",
""
];
var results = tests.map(function(test) {
return balanced(test);
})
var report = JSON.stringify(results, null, 2);
console.log(report);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment