Skip to content

Instantly share code, notes, and snippets.

@danedavid
Created April 4, 2018 05:51
Show Gist options
  • Save danedavid/1f094602ba612f37d6bfddfa23884ae0 to your computer and use it in GitHub Desktop.
Save danedavid/1f094602ba612f37d6bfddfa23884ae0 to your computer and use it in GitHub Desktop.
Function to check for balanced parenthesis in any string using Array.prototype.reduce(). Inspiration: https://medium.freecodecamp.org/check-out-these-useful-ecmascript-2015-es6-tips-and-tricks-6db105590377
const isBalanced = str => {
const arr = str.split('');
const res = arr.reduce((acc, item) => {
if ( acc.slice(-1)[0] === '(' ) {
if ( item === ')' ) {
acc.pop();
return acc;
}
}
if ( item === '(' || item === ')' ) {
acc.push(item);
}
return acc;
}, []);
return res.length ? false : true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment