Last active
March 31, 2016 04:54
-
-
Save yalamber/364f3c4d7baf8cfd87f48344d2215793 to your computer and use it in GitHub Desktop.
This function checks for braces
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 bracesChecker(str) { | |
if(!str) { | |
return true; | |
} | |
var openingBraces = [’{’, ’[’, ’(’]; | |
var closingBraces = [’}’, ’]’, ’)’]; | |
var stack = []; | |
var openIndex; | |
var closeIndex; | |
//check for opening Braces in the val | |
for (var i = 0, len = str.length; i < len; i++) { | |
openIndex = openingBraces.indexOf(str[i]); | |
closeIndex = closingBraces.indexOf(str[i]); | |
if(openIndex !== -1) { | |
stack.push(str[i]); | |
} | |
if(closeIndex !== -1) { | |
if(openingBraces[closeIndex] === stack[stack.length-1]) { | |
stack.pop(); | |
} else { | |
return false; | |
} | |
} | |
} | |
if(stack.length === 0) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
var testStrings = [ | |
'', | |
'test', | |
'{{[][]()()}()}[]()', | |
'{test{[test]}}', | |
'{test{[test]}', | |
'{test{(yo)[test]}}', | |
'test{[test]}}', | |
'te()s[]t{[test]}', | |
'te()s[]t{[test' | |
]; | |
testStrings.forEach(val => console.log(`${val} => ${bracesChecker(val)}`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment