Created
August 4, 2017 12:25
-
-
Save oslego/aa08db841c90416f1371a460974ca990 to your computer and use it in GitHub Desktop.
Method that returns true when a string is balanced and false otherwise.
This file contains 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
/* | |
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