Last active
August 29, 2015 14:20
-
-
Save syzer/74516ccb0f9ca48dfa4a to your computer and use it in GitHub Desktop.
closing tags Maciej chelange
This file contains 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
// 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