Skip to content

Instantly share code, notes, and snippets.

@ryanomor
Created May 3, 2018 03:25
Show Gist options
  • Save ryanomor/8b9150d15cf80f496529fe652401f242 to your computer and use it in GitHub Desktop.
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
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
@chrisdl
Copy link

chrisdl commented May 3, 2018

Good job! Since I'm a pain in the ass here are some more tips:

  • print out your tests or use console.assert(isBalance("something") === true) for easier debugging. the console assert will raise an error if it does not pass.
  • you are using let but I believe all of these variables could be const which is preferred because then you know if it is expected to change or will change.
  • the input string might be null not just empty. So your initial guard is probably simplified as just simply if (!str) return false;
  • I'm not crazy about the name popped. its not bad but I would prefer something like opener, but no biggie.

I think calling it openers is better than calling that variable stack 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

if (allOpeners.includes(char)) {
  openers.push(char)
} else if (allClosers.includes(char)) {
  const lastOpener = openers.pop();
  if (getMatchingOpener(lastOpener) !== char) return false;
}

Anyway, good job!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment