2

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);
2
  • A. This is postfix, not prefix. B. You should just be calling x.pop() with no parameter, and using the results from the pops. Also, you need to create add,subtract, multiply and divide functions that take two parameters each, rather than using +-*/ in your code Commented Sep 4, 2020 at 17:27
  • ah yes, my bad. that's postfix. ok will try it. thank you Commented Sep 6, 2020 at 13:10

1 Answer 1

5

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; }

Sign up to request clarification or add additional context in comments.

3 Comments

Wow this is a remarkably concise implementation! +1
so, we just pull out element from input and push it to new array stack. there's no need to use .pop() ?
yes, but stack.splice(-2, 2) delets the last two values of the stack and returns them in an array. this array is spreaded as parameters for the operation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.