all files / postfix-calculator/ index.js

100% Statements 20/20
100% Branches 7/7
100% Functions 1/1
100% Lines 20/20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37      14×                            
'use strict';
 
function calculate(...args) {
  let stack = [];
 
  args.forEach((arg) => {
    if (parseInt(arg)) {
      stack.push(arg);
    } else {
      const lhs = stack.pop();
      const rhs = stack.pop();
 
      switch (arg) {
        case '+':
          stack.push(rhs + lhs);
          break;
        case '-':
          stack.push(rhs - lhs);
          break;
        case '*':
          stack.push(rhs * lhs);
          break;
        case '/':
          stack.push(rhs / lhs);
          break;
        case '%':
          stack.push(rhs % lhs);
          break;
      }
    }
  });
 
  return stack.pop();
}
 
module.exports = calculate;