Created
December 27, 2016 11:14
-
-
Save WendellAdriel/de4d56190d9a1bfaafcffadec63901dc to your computer and use it in GitHub Desktop.
Function to know if the given string is balanced or not
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
/** | |
* PROBLEM: | |
* Create a function that receives a string like "[[[]]]" or "[][]][" and returns true if the string is balanced | |
* or false if the string isn't (to be balanced the string must have the same number of opening and closing brackets | |
* and they must be in the correct order). For example the first given string must return true and the second one must | |
* return false. | |
*/ | |
const isStringBalanced = string => { | |
return !string.split('').reduce((previous, char) => { | |
if (previous < 0) return previous; | |
if (char === '[') return ++previous; | |
if (char === ']') return --previous; | |
return previous; | |
}, 0); | |
}; | |
console.log(isStringBalanced('[[[]]]')); | |
console.log(isStringBalanced('[][]][')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment