Last active
January 18, 2020 02:01
-
-
Save dfkaye/cf3315d3824da9a53bfd36252bc3e8f2 to your computer and use it in GitHub Desktop.
test for balanced braces, parentheses, brackets
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
// 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