Advertisement
vit134

Обратная польская нотация

Nov 4th, 2018
397
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Обратная польская нотация
  3. */
  4.  
  5. const operators = {
  6.     '+': (x, y) => x + y,
  7.     '-': (x, y) => x - y,
  8.     '*': (x, y) => x * y,
  9.     '/': (x, y) => x / y
  10. };
  11.  
  12. let str = '8 2 5 * + 1 3 2 * + 4 - /'; // 6
  13.  
  14. const calc = str => {
  15.     let stack = [];
  16.  
  17.     str.split(' ').forEach(operator => {
  18.         if (operator in operators) { // если нашли в операторах
  19.             let [y, x] = [stack.pop(), stack.pop()] // берем последние два елемента стэка
  20.             stack.push(operators[operator](x, y)); // и пушим результат функции в стэк
  21.         } else {
  22.             stack.push(parseFloat(operator)); // пушим число в стэк
  23.         }
  24.     })
  25.  
  26.     return stack.pop();
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement