Balanced Brackets Checker Using a Stack

Check whether parentheses, square brackets and braces are balanced and correctly nested with a single-pass stack algorithm.

JavascriptData Integrity

Code

snippet
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;
}