Although a stack is not typically used to store data on a long-term basis, it can be a great tool to handle temporary data as part of various algorithms. Here’s an example:

Let’s create the beginnings of a JavaScript linter—that is, a program that inspects a programmer’s JavaScript code and ensures that each line is syntactically correct. It can be very complicated to create a linter, as there are many different aspects of syntax to inspect.

We’ll focus on just one specific aspect of the linter—opening and closing braces. This includes parentheses, square brackets, and curly braces—all common causes of frustrating syntax errors.

To solve this problem, let’s first analyze what type of syntax is incorrect when it comes to braces. If we break it down, we’ll find that there are three situations of erroneous syntax.

The first is when there is an opening brace that doesn’t have a corresponding closing brace, such as this:

​  (​ var ​ x = 2;

We’ll call this Syntax Error Type #1.

The second is when there is a closing brace that was never preceded by a corresponding opening brace:

​  ​ var ​ x = 2;)

We’ll call that Syntax Error Type #2.

The third, which we’ll refer to as Syntax Error Type #3, is when a closing brace is not the same type of brace as the immediately preceding opening brace, such as:

​  (​ var ​ x = [1, 2, 3)];

In the preceding example, there is a matching set of parentheses, and a matching pair of square brackets, but the closing parenthesis is in the wrong place, as it doesn’t match the immediately preceding opening brace, which is a square bracket.

How can we implement an algorithm that inspects a line of JavaScript code and ensures that there are no brace-related syntax errors? This is where a stack allows us to implement a beautiful linting algorithm, which works as follows:

We prepare an empty stack, and then we read each character from left to right following these rules:

  1. If we find any character that isn’t a type of brace (parenthesis, square bracket, or curly brace), we ignore it and move on.

  2. If we find an opening brace, we push it onto the stack. Having it on the stack means we’re waiting to close that particular brace.

  3. If we find a closing brace, we pop the top element in the stack and inspect it. We then analyze:

    • If the item we popped (which is always an opening brace) does not match the current closing brace, it means we’ve encountered Syntax Error Type #3.

    • If we couldn’t pop an element because the stack was empty, that means the current closing brace doesn’t have a corresponding opening brace beforehand. This is Syntax Error Type #2.

    • If the item we popped is a corresponding match for the current closing brace, it means we’ve successfully closed that opening brace, and we can continue parsing the line of JavaScript code.

  4. If we make it to the end of the line and there’s still something left on the stack, that means there’s an opening brace without a corresponding closing brace, which is Syntax Error Type #1.

Let’s see this in action using the following example:

images/stacks_and_queues/parens_1.png

After we prepare an empty stack, we begin reading each character from left to right.

Step 1: We begin with the first character, which happens to be an opening parenthesis:

images/stacks_and_queues/parens_2.png

Step 2: Since it’s a type of opening brace, we push it onto the stack:

images/stacks_and_queues/push_open_parens.png

We then ignore all the characters, var x = , since they aren’t brace characters.

Step 3: We encounter our next opening brace:

images/stacks_and_queues/parens_3.png

Step 4: We push it onto the stack:

images/stacks_and_queues/push_open_curly_brace.png

We then ignore the y: .

Step 5: We encounter the opening square bracket:

images/stacks_and_queues/parens_4.png

Step 6: We add that to the stack as well:

images/stacks_and_queues/push_open_square_bracket.png

We then ignore the 1, 2, 3 .

Step 7: We encounter our first closing brace—a closing square bracket:

images/stacks_and_queues/first_closing_brace.png

Step 8: We pop the element at the top of the stack, which happens to be an opening square bracket:

images/stacks_and_queues/pop_square_bracket.png

Since our closing square bracket is a corresponding match to this top element of the stack, it means we can continue with our algorithm without throwing any errors.

Step 9: We move on, encountering a closing curly brace:

images/stacks_and_queues/parens_6.png

Step 10: We pop the top item from stack:

images/stacks_and_queues/pop_curly_brace.png

It’s an opening curly brace, so we’ve found a match with the current closing brace.

Step 11: We encounter a closing parenthesis:

images/stacks_and_queues/parens_7.png

Step 12: We pop the last element in the stack. It’s a corresponding match, so there are no errors so far.

Since we’ve made it through the entire line of code, and our stack is empty, our linter can conclude that there are no syntactical errors on this line (relating to opening and closing braces).

Code Implementation: Stack-Based Code Linter

Here’s a Ruby implementation of the preceding algorithm. Note that we are using our earlier Ruby implementation of the Stack class:

​  ​ class ​ Linter
​  
​  ​ def ​ ​ initialize ​
​  ​ # We use a simple array to serve as our stack: ​
​  @stack = Stack.​ new ​
​  ​ end ​
​  
​  ​ def ​ ​ lint ​(text)
​  ​ # We start a loop which reads each character in our text: ​
​  text.​ each_char ​ ​ do ​ |char|
​  
​  ​ # If the character is an opening brace: ​
​  ​ if ​ is_opening_brace?(char)
​  
​  ​ # We push it onto the stack: ​
​  @stack.​ push ​(char)
​  
​  ​ # If the character is a closing brace: ​
​  ​ elsif ​ is_closing_brace?(char)
​  
​  ​ # Pop from stack: ​
​  popped_opening_brace = @stack.​ pop ​
​  
​  ​ # If the stack was empty, so what we popped was nil, ​
​  ​ # it means that an opening brace is missing: ​
​  ​ if ​ !popped_opening_brace
​  ​ return ​ ​ " ​​ #{ ​char​ } ​​ doesn't have opening brace" ​
​  ​ end ​
​  
​  ​ # If the popped opening brace doesn't match the ​
​  ​ # current closing brace, we produce an error: ​
​  ​ if ​ is_not_a_match(popped_opening_brace, char)
​  ​ return ​ ​ " ​​ #{ ​char​ } ​​ has mismatched opening brace" ​
​  ​ end ​
​  ​ end ​
​  ​ end ​
​  
​  ​ # If we get to the end of line, and the stack isn't empty: ​
​  ​ if ​ @stack.​ read ​
​  
​  ​ # It means we have an opening brace without a ​
​  ​ # corresponding closing brace, so we produce an error: ​
​  ​ return ​ ​ " ​​ #{ ​@stack.​ read ​​ } ​​ does not have closing brace" ​
​  ​ end ​
​  
​  ​ # Return true if line has no errors: ​
​  ​ return ​ ​ true ​
​  ​ end ​
​  
​  ​ private ​
​  
​  ​ def ​ ​ is_opening_brace? ​(char)
​  [​ "(" ​, ​ "[" ​, ​ "{" ​].​ include? ​(char)
​  ​ end ​
​  
​  ​ def ​ ​ is_closing_brace? ​(char)
​  [​ ")" ​, ​ "]" ​, ​ "}" ​].​ include? ​(char)
​  ​ end ​
​  
​  ​ def ​ ​ is_not_a_match ​(opening_brace, closing_brace)
​  closing_brace != {​ "(" ​ => ​ ")" ​, ​ "[" ​ => ​ "]" ​, ​ "{" ​ => ​ "}" ​}[opening_brace]
​  ​ end ​
​  ​ end ​

The lint method accepts a string containing JavaScript code and iterates over each character with:

​  text.​ each_char ​ ​ do ​ |char|

If we encounter an opening brace, we push it onto the stack:

​  ​ if ​ is_opening_brace?(char)
​  @stack.​ push ​(char)

Note that we’re using a helper method defined as follows called is_opening_brace? , which checks whether the character is an opening brace:

​  [​ "(" ​, ​ "[" ​, ​ "{" ​].​ include? ​(char)

When we encounter a closing brace, we pop the top of the stack and store it in a variable called popped_opening_brace :

​  popped_opening_brace = @stack.​ pop ​

Our stack only stores opening braces, so whatever we popped will be some sort of opening brace, assuming there was something on the stack to pop.

However, it’s possible the stack was empty, in which case the result of our pop will be nil . If this is the case, it means we’ve encountered Syntax Error Type #2:

​  ​ if ​ !popped_opening_brace
​  ​ return ​ ​ " ​​ #{ ​char​ } ​​ doesn't have opening brace" ​
​  ​ end ​

For simplicity’s sake, we return a basic string containing an error message when we encounter any errors during our linting process.

Assuming that we did pop an opening brace off the stack, we then check it to see whether it matches the current closing brace. If it doesn’t match, this is Syntax Error Type #3:

​  ​ if ​ is_not_a_match(popped_opening_brace, char)
​  ​ return ​ ​ " ​​ #{ ​char​ } ​​ has mismatched opening brace" ​
​  ​ end ​

(The is_not_a_match helper method is defined later in our code.)

Finally, when our code finishes parsing the line, we check whether there are any opening braces left in the stack with @stack.read . If there are, it means we have an opening brace that was never closed, and we produce an error message. This is Syntax Error Type #1:

​  ​ if ​ @stack.​ read ​
​  ​ return ​ ​ " ​​ #{ ​@stack.​ read ​​ } ​​ does not have closing brace" ​
​  ​ end ​

Finally, we return true if the JavaScript contains no errors.

We can then use our Linter class as follows:

​  linter = Linter.​ new ​
​  puts linter.​ lint ​(​ "( var x = { y: [1, 2, 3] } )" ​)

In this example, the JavaScript code is correct, so we just get back true .

However, if we input a line that has an error, such as a missing opening parenthesis:

​  ​ "var x = { y: [1, 2, 3] })" ​

we’ll get the error message, ) doesn’t have opening brace .

In this example, we used a stack to implement our linter with a really neat algorithm. But if a stack actually uses an array under the hood, why bother with a stack? Couldn’t we have accomplished the same task using an array?