Update RPNSolver.md

This commit is contained in:
Rohit Tanwar
2018-01-01 22:10:17 +05:30
committed by GitHub
parent 5bf4b15e1e
commit b208a3c10a

View File

@ -4,13 +4,13 @@ Solves the given reverse polish notation
``` js
const RPNSolver = RPN => {
const operators = {'*' : (a,b) => a * b, '+' : (a,b) => a + b, '-' : (a,b) => a - b, '/' : (a,b) => a / b, '**': (a,b) => a ** b}
let [stack,solve] = [[],RPN.replace(/\^/g,'**').split(/\s+/g).filter(el => !/\s+/.test(el) && el !== '')]
const OPERATORS = {'*' : (a,b) => a * b, '+' : (a,b) => a + b, '-' : (a,b) => a - b, '/' : (a,b) => a / b, '**': (a,b) => a ** b}
const [stack,solve] = [[],RPN.replace(/\^/g,'**').split(/\s+/g).filter(el => !/\s+/.test(el) && el !== '')]
solve.forEach(symbol => {
if(!isNaN(parseFloat(symbol)) && isFinite(symbol)) {stack.push(symbol)}
else if (Object.keys(operators).includes(symbol)) {
let [a,b] = [stack.pop(),stack.pop()]
stack.push(operators[symbol](parseFloat(b),parseFloat(a)))
else if (Object.keys(OPERATORS).includes(symbol)) {
const [a,b] = [stack.pop(),stack.pop()]
stack.push(OPERATORS[symbol](parseFloat(b),parseFloat(a)))
} else { throw `${symbol} is not a recognized symbol` }
}
)