Skip to content

Instantly share code, notes, and snippets.

@korniychuk
Created June 14, 2016 18:42
Show Gist options
  • Save korniychuk/25a8d02a1d92684c0d5c476f92b398e0 to your computer and use it in GitHub Desktop.
Save korniychuk/25a8d02a1d92684c0d5c476f92b398e0 to your computer and use it in GitHub Desktop.
check correct order of the brackets in expression
/**
* @param {string} str testable string
*
* @return {boolean}
*/
function verify(str) {
if (typeof str !== 'string') return false;
var pairs = {
'(' : ')',
'{' : '}',
'<' : '>',
'[' : ']',
};
var reversPairs = {
')' : '(',
'}' : '{',
'>' : '<',
']' : '[',
};
var stack = [];
for (var i = 0, ilen = str.length; i < ilen; i++) {
var char = str.charAt(i);
if (pairs[char] !== undefined) {
stack.push(char);
} else if (reversPairs[char] !== undefined) {
var last = stack.pop();
if (last !== reversPairs[char]) return false;
}
}
return !stack.length;
} // end verify()
console.log('verify("")', verify(""));
console.log('verify("before ( middle []) after ")', verify("before ( middle []) after "));
console.log('verify(") (")', verify(") ("));
console.log('verify("} {")', verify("} {"));
console.log('verify("<( >)")', verify("<( >)"));
console.log('verify("( [ <> () ] <> )")', verify("( [ <> () ] <> )"));
console.log('verify(" ( [)")', verify(" ( [)"));
console.log('verify("---(++++)----")', verify("---(++++)----"));
console.log('verify("")', verify(""));
console.log('verify("before ( middle []) after ")', verify("before ( middle []) after "));
console.log('verify(") (")', verify(") ("));
console.log('verify("} {")', verify("} {"));
console.log('verify("<( >)")', verify("<( >)"));
console.log('verify("( [ <> () ] <> )")', verify("( [ <> () ] <> )"));
console.log('verify(" ( [)")', verify(" ( [)"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment