Skip to content

Instantly share code, notes, and snippets.

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