Skip to content

Instantly share code, notes, and snippets.

@erkobridee
Last active April 14, 2017 02:47
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 erkobridee/4db195fd142a0c4ce81a271a9f77bcd1 to your computer and use it in GitHub Desktop.
Save erkobridee/4db195fd142a0c4ce81a271a9f77bcd1 to your computer and use it in GitHub Desktop.
check balanced parens using Array.reduce function
function balancedParens(string){
return !string.split('').reduce(function(previous, char){
if(previous < 0) { return previous; }
if(char === '(') { return ++previous; }
if(char === ')'){ return --previous; }
return previous;
}, 0);
}
function checkValue(string){
console.log(string, ' : ', balancedParens(string));
}
checkValue('()'); // () : true
checkValue(')('); // )( : false
checkValue('(((())))'); // (((()))) : true
checkValue('())))'); // ()))) : false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment