Last active
August 29, 2015 14:24
-
-
Save arcesino/83fbc5518bfe0272a048 to your computer and use it in GitHub Desktop.
Braces balancer
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
var isBalanced = function(str) { | |
var openers = '{[(<'; | |
var closers = '}])>'; | |
var stack = []; | |
str = str.split(''); | |
for (var i = 0; str.length; i++) { | |
var index; | |
if (openers.indexOf(str[i]) != -1) stack.push(str[i]); | |
else if ((index = closers.indexOf(str[i])) != -1) { | |
if (stack.pop() != openers.charAt(index)) return false; | |
} else { | |
console.log('Unknown character!'); | |
return false; | |
} | |
} | |
return stack.length === 0; | |
}; | |
console.log(isBalanced('{[<><>]}')); // true | |
console.log(isBalanced('{[()]}')); // => true | |
console.log(isBalanced('{[{}][()]}')); // => true | |
console.log(isBalanced('{]}')); // => false | |
console.log(isBalanced(')({}}')); // => false | |
console.log(isBalanced('{{[(<>)]}')); // => false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment