Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Обратная польская нотация
- */
- const operators = {
- '+': (x, y) => x + y,
- '-': (x, y) => x - y,
- '*': (x, y) => x * y,
- '/': (x, y) => x / y
- };
- let str = '8 2 5 * + 1 3 2 * + 4 - /'; // 6
- const calc = str => {
- let stack = [];
- str.split(' ').forEach(operator => {
- if (operator in operators) { // если нашли в операторах
- let [y, x] = [stack.pop(), stack.pop()] // берем последние два елемента стэка
- stack.push(operators[operator](x, y)); // и пушим результат функции в стэк
- } else {
- stack.push(parseFloat(operator)); // пушим число в стэк
- }
- })
- return stack.pop();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement