Created
August 6, 2019 00:25
-
-
Save guizordan/a06809a72b89f08f5e37f7e026527fa4 to your computer and use it in GitHub Desktop.
Checks if a given string has its brackets balanced
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
/** | |
* Tests if the brackets in a given string are balanced | |
* @param {string} expression - the expression string to be tested. | |
*/ | |
function areBracketsBalanced(expression) { | |
if (!expression) { | |
return false; | |
} | |
/** | |
* @type {Array} stack | |
*/ | |
const stack = []; | |
const arePairing = (opening, closing) => | |
(opening == "(" && closing == ")") || | |
(opening == "{" && closing == "}") || | |
(opening == "[" && closing == "]"); | |
const isOpening = char => char == "(" || char == "[" || char == "{"; | |
const isClosing = char => char == ")" || char == "]" || char == "}"; | |
[...expression].forEach(char => { | |
if (isOpening(char)) { | |
stack.push(char); | |
} else if (isClosing(char)) { | |
// assures that closures are occuring in the correct order. | |
if (!stack.length || !arePairing(stack[stack.length - 1], char)) { | |
return false; | |
} else { | |
stack.pop(); | |
} | |
} | |
}); | |
return !stack.length; | |
} | |
// Test cases | |
console.log(Solution("(a[0]+b[2c[6]]){24+53}")); | |
console.log(Solution("f(e(d))")); | |
console.log(Solution("[()]{}([])")); | |
console.log(Solution("((b)")); | |
console.log(Solution("(c]")); | |
console.log(Solution("{(a[])")); | |
console.log(Solution("([(]")); | |
console.log(Solution(")(")); | |
console.log(Solution("")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment