Skip to content

Instantly share code, notes, and snippets.

@guizordan
Created August 6, 2019 00:25
Show Gist options
  • Save guizordan/a06809a72b89f08f5e37f7e026527fa4 to your computer and use it in GitHub Desktop.
Save guizordan/a06809a72b89f08f5e37f7e026527fa4 to your computer and use it in GitHub Desktop.
Checks if a given string has its brackets balanced
/**
* 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