Skip to content

Instantly share code, notes, and snippets.

@WendellAdriel
Created December 27, 2016 11:14
Show Gist options
  • Save WendellAdriel/de4d56190d9a1bfaafcffadec63901dc to your computer and use it in GitHub Desktop.
Save WendellAdriel/de4d56190d9a1bfaafcffadec63901dc to your computer and use it in GitHub Desktop.
Function to know if the given string is balanced or not
/**
* 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