Created
July 4, 2017 14:48
-
-
Save jcready/174095207928ccc666f83a403554ecba to your computer and use it in GitHub Desktop.
Interview Question Answers from https://performancejs.com/post/hde6d32/Big-List-of-Frontend-JavaScript-Interview-Questions-(by-a-Frontend-Engineer)
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
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