Javatpoint Logo
Javatpoint Logo

Calculator using Shunting yard algorithm in HTML using JavaScript

Building a calculator is one of the first challenges to take up when learning JavaScript. We can use different methods to build a calculator like by using eval(), loops etc. There are two tutorials in the website already about how to create a calculator using eval() and using for loops. However, both of those methods aren't that efficient given the security issues the website can face because of the use of eval() and the increased complexity of the code with more number of loops. This tutorial explains one of the efficient methods we can use to build a calculator. We'll be using the Shunting Yard algorithm proposed by Dijkstra to solve the expressions in the calculator for which we'll use two stacks rather than one.

Simple Introduction to HTML, CSS and JS:

  1. HTML is the markup language used to structure a webpage.
  2. CSS is the styling language used to design the layout and look of the elements of the webpage.
  3. JS is the scripting language used to define the behavior and working of the elements in the webpage.

Simple introduction to Shunting Yard Algorithm:

Generally, this algorithm is used to convert an infix expression to postfix also known as Reverse Polish notation (RPN). An expression of the format a + b is an infix notation while the format ab+ is its postfix notation. Evaluating a postfix expression is easy and generally, a computer converts any given infix expression into postfix to evaluate the answer using stacks.

Steps to convert infix to Postfix:

  1. Read the given expression from left to right. If the scanned element is an operand, simply append it to the resultant postfix expression.
  2. If the scanned operator is an operator and the stack is empty, push the operator into the stack
  3. If the scanned element is an operator and the precedence of the operator is greater than or equal to the precedence of the operator on the top of the stack, push it into the stack
  4. If the scanned operator is an operator and the precedence of the scanned operator is less than the precedence of the operator on the top of the stack, pop the operator on the top of the stack and add it to the postfix expression until the stack becomes empty or the precedence of the operator on the top of the stack is less than the precedence of the scanned operator. Now, push the scanned operator into the stack.

For example: 3 + 8 - 9 / 8

Scanned element Stack Postfix notation
3 - 3
+ + 3
8 + 3 8
- - 3 8 +
9 - 3 8 + 9
/ -/ 3 8 + 9
8 -/ 3 8 + 9 8
Postfix expression: 3 8 + 9 8 / -

Evaluating a postfix expression:

Example:

Take the above converted postfix notation. First let us get the result from the infix notation:

3 + 8 - 9 / 8

= 3 + 8 - 1.125

= 11 - 1.125

= 9.875

  • Order of evaluation: Scientific calculator (BODMAS)

Now, let us take the postfix expression we got from the previous conversion:

3 8 + 9 8 / -

  1. Read the expression from left to right, initialize a stack with the same length as the expression.
  2. If the element encountered is an operand, push it into the stack.
  3. If the element encountered is an operator, pop two operands a and b from the stack, apply the operator (b operator a) and push the result back into the stack.
  4. In the above example: 3 8 + 9 8 / -
Calculator using Shunting yard algorithm in HTML using JavaScript

Now, to build a calculator using Shunting yard algorithm, we'll e using two stacks because along with converting to postfix, we also need to evaluate the postfix notation.

Sample HTML and CSS for the Calculator:

CSS:

JavaScript:

  1. On clicking numbers or operators, the value of the button must be displayed on the display.
  2. On clicking on C, the display has to become empty.
  3. On clicking B, the last element on the display must be deleted.
  4. On clicking =, everything on the display must be solved and now the display has to show the result of the expression entered.

Hence, we need to write 4 functions in JavaScript for the functionalities of four types of buttons.

You can style the calculator anyway you want using CSS. For simplicity, we aren't using much styling features. We'll create the calculator in the same design as in the tutorial where we used eval() to create the calculator.

We'll make a calculator like this:

Calculator using Shunting yard algorithm in HTML using JavaScript
  • We used io to develop the code. You can use a text editor or any software you want.

Code:

Rather than bringing out the whole code at once, let us break it down. First, the displaying part:

  1. fun(a):
    • On clicking all the buttons of numbers and operators, we call fun () with the value of the number or operator as argument.
    • In the function, we need to print that value on the display input box, hence, we concatenate the argument to the value already in the input box.
  2. C(): We'll simply reassign the value of the display input box to an empty string to clear the display.
  3. B(): We'll get the whole string on the display and slice it deleting the last element and re-assign it to the display again.
  4. res(): This function is activated on clicking =.

Using trim(), we're getting rid of any extra unnecessary spaces and then, the expression is given as input to another function fun1().

fun1():

This function contains the actual functionality or the backend of the calculator after taking the expression as input:

Code:

Explanation:

  1. We declared two arrays (stacks), values[] and operators[].
  2. opc and clc stand for opening braces and closing braces.
  3. In the next for loop, we've checked if the number of opening braces is equal to the number of closing braces. Else, it returns that the expression provided is invalid.
  4. According to BODMAS, we need to first solve the sub-expressions inside brackets, hence, we check if there are any brackets and if there are, we extract the sub-expression between the brackets and call fun1() again with the sub-expression as input.
  5. This recursion continues if there are any brackets in the expression.
  6. Now, coming to the actual solving part:
    1. We check if there is a preceding sign to the expression, if there is any, we push a 0 into values. Suppose, if expression is -8: 0-8 is still -8.
    2. Then, we checked if there are consecutive operators which return invalid expression again.
    3. If there is an operand, push it into the values stack
    4. Now, if there is an operator:
      1. If the operators stack is empty, push the operator into the stack
      2. If the precedence of the operator found is greater than the precedence of the operator on the top of the operators stack, push the operator into the stack
      3. If the precedence of the operator found is less than or equal to the operator on the top of the operators stack, pop the last operator from the operators stack and two operands from the values stack and perform the operation on the two operands and push the result into the values stack.
      4. Continue the process until the precedence of the operator found is greater than the precedence of the operator on the top of the stack.
  7. Now, we handled a situation where + and - can be consecutive. This usually occurs where there are brackets: 3 + (2 - 3) -> 3 + - 1 -> 2
  8. In that scenario, we get the operand along with the - sign, convert it into float and push it into values stack like a regular operand.
  9. Finally, if the operators stack isn't empty which means there are still a few operators and values left, pop out the operands from the values stack and apply the operator on the top of the operators stack and pop the operator from the operators stack.
  10. Continue the process until there are no operators and operands left in the operators and values stack.
  11. The function precedence is to manage the precedence rules as in BODMAS/ PEDMAS

Example:

Expression: 3 + (5 + 9 * 9)

  1. The expression between the parenthesis is passed again to the function:
    • 5 is pushed into the values stack
    • + is pushed into the operators stack
    • 9 is pushed into the values stack
    • The precedence of * is greater than +, so, it is pushed into the values stack
    • 9 is pushed into the values stack.
      Values:
      Calculator using Shunting yard algorithm in HTML using JavaScript
      Operators:
    • Pop two operands from values stack: 9 9 and apply the operator at the top of the operators stack: 9 * 9 = 81. Push 81 into the values stack:
      Calculator using Shunting yard algorithm in HTML using JavaScript
      81 + 5 = 86.
  2. Now, 86 is concatenated to the original string in the place of the expression within parenthesis
  3. Expression: 3 + 86
  4. 3 is pushed into the values stack.
  5. + is pushed into the operators stack
  6. 86 is pushed into the values stack
    Calculator using Shunting yard algorithm in HTML using JavaScript
  7. 86 + 3 = 89 is the final result.

Output Screens:

Calculator using Shunting yard algorithm in HTML using JavaScript
Calculator using Shunting yard algorithm in HTML using JavaScript





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA