Created
April 4, 2018 05:51
-
-
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
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
| 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