Created
May 3, 2018 03:25
-
-
Save ryanomor/8b9150d15cf80f496529fe652401f242 to your computer and use it in GitHub Desktop.
Create a function that checks if parentheses and brackets are correctly balanced in a string
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
var isBalance = function(str) { | |
if(str.length < 1) return false; | |
let pairs = { | |
'(': ')', | |
'{': '}', | |
'[': ']' | |
}; | |
let openers = []; // replace [] with: new Stack | |
for (let index in str) { | |
let char = str[index]; | |
if (pairs[char]) { | |
openers.push(char); | |
} else if (Object.values(pairs).includes(char)) { | |
let popped = openers.pop(); | |
if(pairs[popped] != char) { | |
return false; | |
} | |
} | |
} | |
return openers.length == 0; | |
} | |
//test cases | |
isBalance('({}())') // true | |
isBalance('({)}') // false | |
isBalance('(this{works})') // true | |
isBalance('[[()') // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good job! Since I'm a pain in the ass here are some more tips:
console.assert(isBalance("something") === true)
for easier debugging. the console assert will raise an error if it does not pass.let
but I believe all of these variables could beconst
which is preferred because then you know if it is expected to change or will change.null
not just empty. So your initial guard is probably simplified as just simplyif (!str) return false;
opener
, but no biggie.I think calling it
openers
is better than calling that variablestack
although each has its own advantages.One recommendation for more readable code might be to have allOpeners and allClosers arrays, that way we can write it like this
Anyway, good job!