Skip to content

Instantly share code, notes, and snippets.

@jcready
Created July 4, 2017 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcready/174095207928ccc666f83a403554ecba to your computer and use it in GitHub Desktop.
Save jcready/174095207928ccc666f83a403554ecba to your computer and use it in GitHub Desktop.
isBalanced = (() => {
const braces = {
'{': [ 0, 1 ],
'}': [ 0, -1 ],
'[': [ 1, 1 ],
']': [ 1, -1 ],
'(': [ 2, 1 ],
')': [ 2, -1 ]
}
return function isBalanced (s) {
const counts = [ 0, 0, 0 ]
const order = []
for (let c of s) {
if (!braces.hasOwnProperty(c)) continue;
const [ type, value ] = braces[c]
counts[type] += value
if (value < 0 && order.pop() !== type) {
return false
} else if (value > 0) {
order.push(type)
}
}
return !order.length
}
})()
/* Test */
isBalanced('(foo { bar (baz) [boo] })') // true
isBalanced('foo { bar { baz }') // false
isBalanced('foo { (bar [baz] } )') // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment