Skip to content

Instantly share code, notes, and snippets.

@syzer
Last active August 29, 2015 14:20
Show Gist options
  • Save syzer/74516ccb0f9ca48dfa4a to your computer and use it in GitHub Desktop.
Save syzer/74516ccb0f9ca48dfa4a to your computer and use it in GitHub Desktop.
closing tags Maciej chelange
// char => char
function closingTag(char) {
return {
'(': ')',
'{': '}',
'[': ']'
}[char];
}
// char => boolean
function isClosingTag(c) {
return c === ')' || c === ']' || c === '}';
}
// array, string => array
function notMatchingTags(openTags, tag) {
if (isClosingTag(tag)) {
if (tag === closingTag(openTags[openTags.length - 1])) {
openTags.pop();
} else {
openTags.push('X'); // special char no closing to match
}
} else {
openTags.push(tag);
}
return openTags;
}
// str => boolean
function isValidParenthesis(str) {
return str.split('').reduce(notMatchingTags, []).length === 0;
}
console.log(isValidParenthesis("{}")) //true
console.log(isValidParenthesis("{]")) //false
console.log(isValidParenthesis("{{}}")) //true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment