Advertisement
simeonshopov

Jan's Notation

Mar 23rd, 2021
556
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(arr) {
  2.   let operands = [];
  3.   let operators = [];
  4.  
  5.   for (const ele of arr) {
  6.     if (checkNumberOrNot(ele)) {
  7.       operands.push(ele);
  8.     } else {
  9.       if (operands.length > 1) {
  10.         const operand2 = operands.pop();
  11.         const operand1 = operands.pop();
  12.         let newOperand = calculate(operand1, operand2, ele);
  13.         operands.push(newOperand);
  14.       } else {
  15.         operators.push(ele);
  16.       }
  17.     }
  18.   }
  19.  
  20.   let breakCondition = (operands.length !== operators.length)? "Error: too many operands!" : "Error: not enough operands!";
  21.   return (operands.length === 1 && operators.length == 0)? operands[0]: breakCondition;
  22.  
  23.   function calculate(a, b, op) {
  24.     if (op === '+') {
  25.       return a + b;
  26.     }else if (op === '-') {
  27.       return a - b;
  28.     } else if (op === '*') {
  29.       return a * b;
  30.     } else if (op === '/') {
  31.       return a / b;
  32.     }
  33.   }
  34.  
  35.   function checkNumberOrNot(x) {
  36.     if (typeof x === 'number') {
  37.       return true;
  38.     } else {
  39.       return false;
  40.     }
  41.   }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement