Balanced Brackets Checker Using a Stack
Check whether parentheses, square brackets and braces are balanced and correctly nested with a single-pass stack algorithm.
Code
const PAIRS = new Map([
[")", "("],
["]", "["],
["}", "{"],
]);
export function isBalanced(input) {
if (typeof input !== "string") throw new TypeError("input must be a string");
const stack = [];
for (const char of input) {
if ("([{".includes(char)) {
stack.push(char);
} else if (PAIRS.has(char)) {
if (stack.pop() !== PAIRS.get(char)) return false;
}
}
return stack.length === 0;
}Report a problem with this exampleOpens a pre-filled issue on GitHub.