-
-
Save olivmonnier/ef737cf7f7683749b76b1fffe3dc1a1a to your computer and use it in GitHub Desktop.
Balanced parentheses solution with implicit state
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
| function balanced (string) { | |
| const iterator = string[Symbol.iterator](); | |
| return balancedIterator(iterator) === true; | |
| } | |
| const CLOSE = { | |
| '(': ')', | |
| '[': ']', | |
| '{': '}' | |
| }; | |
| function balancedIterator(iterator) { | |
| while (true) { | |
| const { value: token, done } = iterator.next(); | |
| if (done) { | |
| return true; | |
| } else if (!!CLOSE[token]) { | |
| const nextToken = balancedIterator(iterator); | |
| if (nextToken !== CLOSE[token]) { | |
| return false; | |
| } | |
| } else { | |
| return token; | |
| } | |
| } | |
| } | |
| function test (examples) { | |
| for (const example of examples) { | |
| console.log(`'${example}' => ${balanced(example)}`); | |
| } | |
| } | |
| test(['', '()', '(){}', | |
| '([()()]())', '([()())())', | |
| '())()', '((())(())' | |
| ]); | |
| //=> | |
| '' => true | |
| '()' => true | |
| '(){}' => true | |
| '([()()]())' => true | |
| '([()())())' => false | |
| '())()' => false | |
| '((())(())' => false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment