Created
June 12, 2016 03:51
-
-
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.
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
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