Stack-brackets to validate Brackets function in JavaScript

Stack-brackets to validate Brackets function in JavaScript

As a JavaScript developer, I have often come across the need to validate brackets in strings of code. This is especially important when we are dealing with complex expressions, as it can become difficult to keep track of opening and closing brackets.

One way to validate brackets in JavaScript is by using a stack. A stack is a data structure that allows us to keep track of elements in a Last In First Out (LIFO) order. In our case, we can push opening brackets onto the stack and pop them off when we encounter their closing counterpart. If the stack is empty at the end of the string, we know that all brackets have been properly closed.

Code Implementation

Let's take a look at an implementation of this algorithm in JavaScript:


function validateBrackets(str) {
  const stack = [];
  
  for (let i = 0; i < str.length; i++) {
    const char = str[i];
    
    if (char === '(' || char === '[' || char === '{') {
      stack.push(char);
    } else if (char === ')' && stack[stack.length - 1] === '(') {
      stack.pop();
    } else if (char === ']' && stack[stack.length - 1] === '[') {
      stack.pop();
    } else if (char === '}' && stack[stack.length - 1] === '{') {
      stack.pop();
    } else {
      return false;
    }
  }
  
  return stack.length === 0;
}

console.log(validateBrackets("(foo { bar (baz) [boo] })")); // true
console.log(validateBrackets("((foo { bar (baz) [boo] }))")); // false

In this implementation, we loop through each character in the string and check if it is an opening or closing bracket. If it is an opening bracket, we push it onto the stack. If it is a closing bracket, we check if it matches the top of the stack. If it does, we pop the bracket off the stack. If it doesn't match or the stack is empty, we return false. Finally, if the stack is empty at the end of the loop, we return true.

Alternative Approaches

There are several other ways to validate brackets in JavaScript. One alternative approach is to use recursion to check each pair of brackets. Another approach is to use regular expressions to sanitize the string and then count the number of opening and closing brackets to ensure they match.


// Recursion approach
function validateBrackets(str) {
  if (!str) {
    return true;
  }
  
  const firstOpening = str.indexOf('(');
  const firstClosing = str.indexOf(')');
  
  if (firstClosing < firstOpening) {
    return false;
  }
  
  return validateBrackets(str.substring(firstOpening + 1, firstClosing)) &&
         validateBrackets(str.substring(firstClosing + 1));
}

console.log(validateBrackets("(foo { bar (baz) [boo] })")); // true
console.log(validateBrackets("((foo { bar (baz) [boo] }))")); // false

// Regular expression approach
function validateBrackets(str) {
  const sanitizedStr = str.replace(/[^\(\)\[\]\{\}]/g, '');
  
  const openingBrackets = sanitizedStr.match(/\(|\[|\{/g);
  const closingBrackets = sanitizedStr.match(/\)|\]|\}/g);
  
  if (!openingBrackets || !closingBrackets || openingBrackets.length !== closingBrackets.length) {
    return false;
  }
  
  return true;
}

console.log(validateBrackets("(foo { bar (baz) [boo] })")); // true
console.log(validateBrackets("((foo { bar (baz) [boo] }))")); // false

Each approach has its own pros and cons, and the choice ultimately depends on the specific requirements of the project.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe