Spocoman

06. Operations Between Numbers

Dec 20th, 2021 (edited)
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function OperationsBetweenNumbers(input) {
  2.     let num1 = Number(input[0]);
  3.     let num2 = Number(input[1]);
  4.     let symbol = input[2];
  5.     let number = "";
  6.     let sum = 0;
  7.  
  8.     if (symbol === "+" || symbol === "-" || symbol === "*") {
  9.         if (symbol === "+") {
  10.             sum = num1 + num2;
  11.         } else if (symbol === "-") {
  12.             sum = num1 - num2;
  13.         } else {
  14.             sum = num1 * num2;
  15.         }
  16.         if (sum % 2 === 0) {
  17.             number = "even";
  18.         } else {
  19.             number = "odd";
  20.         }
  21.         console.log(`${num1} ${symbol} ${num2} = ${sum} - ${number}`);
  22.     } else {
  23.         if (num2 === 0) {
  24.             console.log(`Cannot divide ${num1} by zero`);
  25.         } else {
  26.             if (symbol === "/") {
  27.                 sum = num1 / num2;
  28.                 console.log(`${num1} / ${num2} = ${sum.toFixed(2)}`);
  29.             } else if (symbol === "%") {
  30.                 sum = num1 % num2;
  31.                 console.log(`${num1} % ${num2} = ${sum}`);
  32.             }
  33.         }
  34.     }
  35. }
  36.  
  37. Решение с тернарен оператор:
  38.  
  39. function OperationsBetweenNumbers(input) {
  40.     let num1 = Number(input[0]);
  41.     let num2 = Number(input[1]);
  42.     let symbol = input[2];
  43.  
  44.     let sum =
  45.         symbol === "+" ? num1 + num2 :
  46.         symbol === "-" ? num1 - num2 :
  47.         symbol === "*" ? num1 * num2 :
  48.         symbol === "/" && num2 !== 0 ? num1 / num2 :
  49.         symbol === "%" && num2 !== 0 ? num1 % num2 : 0;
  50.  
  51.     let number = sum % 2 === 0 ? "even" : "odd";
  52.  
  53.     if (symbol === "+" || symbol === "-" || symbol === "*") {
  54.         console.log(`${num1} ${symbol} ${num2} = ${sum} - ${number}`);
  55.     } else if (symbol === "/" || symbol === "%") {
  56.         console.log(num2 === 0 ? `Cannot divide ${num1} by zero` :
  57.             `${num1} ${symbol} ${num2} = ${symbol === "/" ? sum.toFixed(2) : sum}`);
  58.     }
  59. }
  60.  
Add Comment
Please, Sign In to add comment