Skip to content

Instantly share code, notes, and snippets.

@jonfriesen
Created June 12, 2016 03:51
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 jonfriesen/b232c9678422d2dfd682dcec0d715d7f to your computer and use it in GitHub Desktop.
Save jonfriesen/b232c9678422d2dfd682dcec0d715d7f to your computer and use it in GitHub Desktop.
Simple kata for finding if a string has balanced braces (no other characters). Solves a simple programming interview question a friend had to do.
function isArrayBalanced(inputArray) {
function isBalanced(input) {
Array.prototype.peek = function() {
return this[this.length - 1];
};
if (input.length % 2 !== 0) return "NO";
var braceStack = [];
var braceMap = {
"}" : "{",
"]" : "[",
")" : "("
};
var closingBraces = "}])", openingBraces = "{[(";
for (var i = 0; i < input.length; i++) {
// input.forEach(function(character){
if (openingBraces.indexOf(input[i]) > -1) {
braceStack.push(input[i]);
}
if (closingBraces.indexOf(input[i]) > -1) {
if(braceStack.peek() === braceMap[input[i]]) {
// This is good, everything matches
// pop the stack and continue
braceStack.pop();
} else {
return "NO";
}
}
};
if (braceStack.length > 0) return "NO";
return "YES";
}
var newArr = [];
inputArray.forEach(function(input){
newArr.push(isBalanced(input));
});
return newArr;
}
console.log(isArrayBalanced(["[()]", "[]", "[[]]]", "({[}])"]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment