georgiev955

Jan's Notation

Sep 20th, 2023
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input) {
  2.     let result = [];
  3.  
  4.     let parser = {
  5.         '+': function sum(num1, num2) {
  6.             result.push(num1 + num2);
  7.         },
  8.         '-': function subtract(num1, num2) {
  9.             result.push(num1 - num2);
  10.         },
  11.         '*': function multiply(num1, num2) {
  12.             result.push(num1 * num2);
  13.         },
  14.         '/': function divide(num1, num2) {
  15.             result.push(num1 / num2);
  16.         }
  17.     }
  18.  
  19.     for (const el of input) {
  20.         if (typeof (el) === 'number') {
  21.             result.push(el);
  22.         } else {
  23.             let lastNumber = result.pop();
  24.             let secondLast = result.pop();
  25.             if (lastNumber && secondLast) {
  26.                 parser[el](secondLast, lastNumber);
  27.             } else {
  28.                 return 'Error: not enough operands!';
  29.             }
  30.         }
  31.     }
  32.  
  33.     if (result.length > 1) {
  34.         return 'Error: too many operands!';
  35.     } else {
  36.         return result[0];
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment