Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Method that returns true when a string is balanced and false otherwise.
/*
Task:
Given an input string return true if the string is balanced, otherwise return false.
A string is balanced when every opening bracket "{", square bracket "[", and parenthesis "("
has a matching closing character.
*/
const string = "{[()]}";
(function(input){
const openers = ['{', '[' ,'('];
const closers = ['}', ']' ,')'];
// If `unmatchedChars` length is non-zero, input is not balanced.
const unmatchedChars = input.split('').reduce((acc, char, i) => {
if (openers.includes(char)) {
acc.push(char)
}
if (closers.includes(char)) {
const indexOfCloser = closers.indexOf(char);
const opener = openers[indexOfCloser];
if (acc[acc.length - 1] === opener) {
acc.pop()
}
}
return acc;
}, [])
// console.log(unmatchedChars.length === 0)
const accumulator = [];
// If `isNotBalanced` is `false`, the `input` IS balanced. Observe the double negative!
// Array.some() method ensures early exit if a mismatch if found, so there's no need to parse the rest of the input.
const isNotBalanced = input.split('').some((char, i) => {
if (openers.includes(char)) {
accumulator.push(char);
}
if (closers.includes(char)) {
const closerIndex = closers.indexOf(char);
const opener = openers[closerIndex];
if (accumulator[accumulator.length-1] === opener) {
accumulator.pop();
} else {
return true;
}
}
return false;
})
// console.log(!isNotBalanced)
})(string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.