Prefix calculator using stack in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to make a calculator with the RPN (reverse polish notation) input method using Stacks in JavaScript.

Consider the following input array −

const arr = [1, 5, '+', 6, 3, '-', '/', 7, '*'];

Process −

  • 1 is an operand, push to Stack.

  • 5 is an operand, push to Stack.

  • '+' is an operator, pop 1 and 5, calculate them and push result to Stack.

  • 6 is an operand, push to Stack.

  • 3 is an operand, push to Stack.

  • '−' is an operator, pop 6 and 3, subtract them and push result to Stack.

  • '/' is an operator, pop 6 and 3, divided them and push result to Stack.

  • 7 is an operand, push to Stack.

  • '*' is an operator, pop 2 and 7, multiply them and push result to Stack.

And finally, the output should be −

const output = 14;

Example

The code for this will be −

const arr = [1, 5, '+', 6, 3, '−', '/', 7, '*'];
const stackCalculator = (arr = []) => {
   const options = {
      '+': (a, b) => a + b,
      '−': (a, b) => a - b,
      '*': (a, b) => a * b,
      '/': (a, b) => a / b
   };
   const stack = [];
   arr.forEach(value => {
      stack.push(value in options
      ? options[value](...stack.splice(-2))
      : value
      );
   });
   return stack;
};
console.log(stackCalculator(arr));

Output

And the output in the console will be −

[14]
raja
Published on 23-Nov-2020 11:16:31
Advertisements