Guest User

Untitled

a guest
Jan 18th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. function claculate(str) {
  2. let numbersStack = [];
  3. let operatorsStack = [];
  4. let operators = {
  5. '+' : {
  6. order : 1,
  7. func : (r,l) => {return l+r;}
  8. },
  9. '-' : {
  10. order : 1,
  11. func : (r,l) => {return l-r;}
  12. },
  13. '*' : {
  14. order : 2,
  15. func : (r,l) => {return l*r;}
  16. },
  17. '/' : {
  18. order : 2,
  19. func : (r,l) => {return l/r;}
  20. },
  21. '^' : {
  22. order : 3,
  23. func : (r,l) => {return Math.pow(r,l);}
  24. },
  25. '(' : {
  26. order: 0
  27. }
  28. }
  29.  
  30. for (let i=0; i<str.length; ++i) {
  31. if (str[i] === ' ') continue;
  32.  
  33. // read the numbers
  34. if (!isNaN(str[i])) {
  35. let tmp = "";
  36. // more then single digit
  37. while (!isNaN(str[i])) {
  38. tmp += str[i++];
  39. }
  40. numbersStack.push(parseInt(tmp));
  41. }
  42.  
  43. if (str[i] === '(') {
  44. operatorsStack.push(str[i]);
  45. } else if (str[i] === ')') {
  46. // calculate the expression in the parentheses
  47. while (operatorsStack[operatorsStack.length - 1] !== '(') {
  48. numbersStack.push(operators[operatorsStack.pop()].func(numbersStack.pop(),numbersStack.pop()));
  49. }
  50. operatorsStack.pop();
  51. } else if (Object.keys(operators).indexOf(str[i]) !== -1) {
  52. // keep the order of execution
  53. while (operatorsStack.length !== 0 && operators[operatorsStack[operatorsStack.length - 1]].order >= operators[str[i]].order) {
  54. numbersStack.push(operators[operatorsStack.pop()].func(numbersStack.pop(),numbersStack.pop()));
  55. }
  56. operatorsStack.push(str[i]);
  57. }
  58. }
  59.  
  60. // calculate remaining operators
  61. while(operatorsStack.length !== 0) {
  62. numbersStack.push(operators[operatorsStack.pop()].func(numbersStack.pop(),numbersStack.pop()));
  63. }
  64.  
  65. // last remaning element is the result
  66. return numbersStack.pop();
  67. }
  68.  
  69. console.log(claculate("2+4")) // 6
  70. console.log(claculate("1+2 * 3")) // 7
  71. console.log(claculate("2 * (3 - 1)^4")) // 32
Add Comment
Please, Sign In to add comment