Skip to content

Instantly share code, notes, and snippets.

@r37r0m0d3l
Created March 24, 2018 21:21
Show Gist options
  • Select an option

  • Save r37r0m0d3l/f2923ce057c5b81c55f14eae938f921f to your computer and use it in GitHub Desktop.

Select an option

Save r37r0m0d3l/f2923ce057c5b81c55f14eae938f921f to your computer and use it in GitHub Desktop.
//Returns 0 if balanced.
const isParensBalanced = (str) => {
return str.split('').reduce((counter, char) => {
if(counter < 0) { //matched ")" before "("
return counter;
} else if(char === '(') {
return ++counter;
} else if(char === ')') {
return --counter;
} else { //matched some other char
return counter;
}
}, 0); //<-- starting value of the counter
}
isParensBalanced('(())') // 0 <-- balanced
isParensBalanced('(asdfds)') //0 <-- balanced
isParensBalanced('(()') // 1 <-- not balanced
isParensBalanced(')(') // -1 <-- not balanced
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment