Parse With The Shunting Yard Algorithm Using JavaScript

Anyone who knows how to program can probably solve a mathematical equation such as 5 + 3 * 6 - ( 5 / 3 ) + 7, but how might you get a computer to understand the appropriate order of operations? The equation I listed is in a format known as Infix Notation.

Infix notation is the notation commonly used in arithmetical and logical formulae and statements. It is characterized by the placement of operators between operands.

This format is not the most ideal to work with when attempting to solve.

Instead it is more appropriate to use format such as 5 3 6 * + 5 3 / - 7 + which is more commonly known as Postfix Notation or Reverse Polish Notation (RPN). This conversion can be accomplished by what is known as the Shunting Yard algorithm.

A method for parsing mathematical expressions specified in infix notation. It can be used to produce output in Reverse Polish notation (RPN).

We’re going to explore how to implement this algorithm using JavaScript. However, we won’t be solving the Reverse Polish Notation result in this article. We will only be parsing to RPN or Postfix Notation.

The logic behind this algorithm will be as follows:

Split the infix string based on any operator

Loop through the split infix token array

If the token is numeric add it to the postfix string

If the token is a ^*/+- operator check its level of precedence compared to the last found operator and pop from the operator stack appropriately

If the token is an opening parenthesis add it to the operator stack

If the token is a closing parenthesis, pop all operators from the stack up to the opening parenthesis

Pop all remaining operators into the postfix result string

In JavaScript we’re missing a few required functions, so it is a good idea to add them before we do anything:

Conclusion

The Shunting Yard algorithm is a very good way to prepare mathematical equations for solving. It will convert your Infix Notation string into a more readable Postfix Notation / Reverse Polish Notation string. If you’re looking for a job in software engineering, this is also a very good interview question for an onsite interview because it will thoroughly test your problem solving skills.

If you think you can beat my version of the algorithm or have been asked a variant of this in an interview, I encourage you to share in the comments section.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.