Skip to content

Instantly share code, notes, and snippets.

@yalamber
Last active March 31, 2016 04:54
Show Gist options
  • Save yalamber/364f3c4d7baf8cfd87f48344d2215793 to your computer and use it in GitHub Desktop.
Save yalamber/364f3c4d7baf8cfd87f48344d2215793 to your computer and use it in GitHub Desktop.
This function checks for braces
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