Last active
July 29, 2020 14:38
-
-
Save karol-majewski/afaff207cd2c22656bd8262ee263826b to your computer and use it in GitHub Desktop.
Creating exhaustive records with TypeScript (parenthesis matching problem, https://medium.com/@paulrohan/parenthesis-matching-problem-in-javascript-the-hacking-school-hyd-7d7708278911)
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
type Opening = '(' | '{' | '['; | |
type Closing = ')' | '}' | ']'; | |
type Parenthesis = Opening | Closing; | |
const parentheses: Record<Opening, Closing> = { | |
'(': ')', | |
'[': ']', | |
'{': '}', | |
}; | |
const isOpening = (parenthesis: Parenthesis): parenthesis is Opening => | |
parenthesis in parentheses; | |
const matches = (word: string): boolean => { | |
const stack: Opening[] = []; | |
for (let i = 0; i < word.length; i++) { | |
const char = word[i] as Parenthesis; | |
if (isOpening(char)) { | |
stack.push(char); | |
} else { | |
const last = stack.pop(); | |
if (last === undefined || char !== parentheses[last]) { | |
return false; | |
} | |
} | |
} | |
if (stack.length !== 0) { | |
return false; | |
} | |
return true; | |
} | |
console.log(matches("(){}")); // true | |
console.log(matches("[{()()}({[]})]({}[({})])((((((()[])){}))[]{{{({({({{{{{{}}}}}})})})}}}))[][][]")); // true | |
console.log(matches("({(()))}}")); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Same, but matching HTML tags. This version returns the first tag that needs to be changed.