Last active
February 15, 2019 08:31
-
-
Save raganwald/fdf5f1f558884117817cd0c99c971dde to your computer and use it in GitHub Desktop.
Balanced parentheses solution with implicit state
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
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