prefix calculator using stack in javascript

Viewed 1130

i'm trying to make calculator with RPN (reverse polish notation) input method using stack in javascript.

input : [1, 5, '+', 6, 3, '-', '/', 7, '*']

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.

output : [14]

is there any other alternative to make my code more effective?

const x1 = x.push(1);
const x2 = x.push(5);
const x3 = x.push('+');

x.pop(1);
x.pop(5);
x.pop('+');
x.push(1+5);

const x4 = x.push(6);
const x5 = x.push(3);
const x6 = x.push('-');

x.pop(6);
x.pop(3);
x.pop('-');
x.push(6-3);

const x7 = x.push('/');
x.pop(6);
x.pop(3);
x.pop('/');
x.push(6/3);

const x8 = x.push(7);
const x9 = x.push('*');

x.pop(2);
x.pop(7);
x.pop('*');
x.push(2*7);

console.log(x);
1 Answers

You could take an object for all operators and check if the value of input is an operator, then perform the operation with the reversed popped values of the stack or push the value to the stack.

const
    operators = {
        '+': (a, b) => a + b,
        '-': (a, b) => a - b,
        '*': (a, b) => a * b,
        '/': (a, b) => a / b
    },
    input = [1, 5, '+', 6, 3, '-', '/', 7, '*'],
    stack = [];

input.forEach(value => {
    stack.push(value in operators
        ? operators[value](...stack.splice(-2))
        : value
    );
    console.log(...stack);
});
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related