Advertisement
simonradev

Stack

Feb 11th, 2018
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function main(allInstructions) {
  2.     const AvailableOperations = {
  3.         ['+']: (a, b) => a + b,
  4.         ['-']: (a, b) => a - b,
  5.         ['*']: (a, b) => a * b,
  6.         ['/']: (a, b) => a / b,
  7.     }    
  8.  
  9.     const stack = [];
  10.  
  11.     for (const instruction of allInstructions) {
  12.         const number = Number(instruction);
  13.  
  14.         if (isNumber(number)) {
  15.             stack.push(number);
  16.         } else {
  17.             if (notEnoughNumbersInStack(stack)) {
  18.                 console.log('Error: not enough operands!');
  19.                 return; // potential bug
  20.             }
  21.  
  22.             const rightOperand = stack.pop();
  23.             const leftOperand = stack.pop();
  24.  
  25.             const currentOperation = AvailableOperations[instruction];
  26.  
  27.             const result = currentOperation(leftOperand, rightOperand);
  28.  
  29.             stack.push(result);
  30.         }
  31.     }
  32.  
  33.     if (stack.length === 1) {
  34.         console.log(stack.pop());
  35.     } else {
  36.         console.log('Error: too many operands!');
  37.     }
  38.  
  39.     function isNumber(potentialNumber) {
  40.         return !isNaN(potentialNumber);
  41.     }
  42.  
  43.     function notEnoughNumbersInStack(stack) {
  44.         return stack.length < 2;
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement