Created
March 24, 2018 21:21
-
-
Save r37r0m0d3l/f2923ce057c5b81c55f14eae938f921f to your computer and use it in GitHub Desktop.
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
| //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