Advertisement
Elfik

Simple calculator

Nov 2nd, 2023
577
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function calculator(stringCalculation) {
  2.   let numbers = []
  3.   let operators = []
  4.   let currentDigits = ''
  5.  
  6.   for (let i = 0; i < stringCalculation.length + 1; i++) {
  7.     const currentSymbol = stringCalculation[i]
  8.     const number = parseInt(currentSymbol)
  9.    
  10.     if (Number.isNaN(number)) {
  11.       numbers.push(parseInt(currentDigits))
  12.      
  13.       if (currentSymbol) {
  14.         operators.push(currentSymbol)
  15.       }
  16.  
  17.       currentDigits = ''
  18.     } else {
  19.       currentDigits += number
  20.     }
  21.   }
  22.  
  23.   return calculate(numbers, operators)
  24. }
  25.  
  26. function action(arg1, arg2, operator) {
  27.   switch (operator) {
  28.     case "+":
  29.       return arg1 + arg2;
  30.     case "*":
  31.       return arg1 * arg2;
  32.   }
  33.  
  34.   return 0
  35. }
  36.  
  37. const symbolPriority = ['*', ':', '+', '-']
  38.  
  39. function calculate(numbers, operators) {
  40.   if (operators.length === 0) {
  41.     return numbers[0] ?? 0
  42.   }
  43.  
  44.   let index = -1
  45.   for (let i = 0; i < symbolPriority.length; i++) {
  46.     index = operators.indexOf(symbolPriority[i])
  47.     if (index !== -1) {
  48.       break;
  49.     }
  50.   }
  51.    
  52.   const firstPart = numbers.slice(0, index)
  53.   const secondPart = numbers.slice(index + 2)
  54.   const localResult = action(numbers[index], numbers[index + 1], operators[index])
  55.  
  56.   const newNumbers = [...firstPart, localResult, ...secondPart]
  57.   const newOperators = operators.filter((_, idx) => idx !== index)
  58.  
  59.   return calculate(newNumbers, newOperators)
  60. }
  61.  
  62. calculator("11+2*3+4")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement