add RPN solver

This commit is contained in:
Rohit Tanwar
2018-01-01 20:51:01 +05:30
parent 4caaa2a0d2
commit 568346beb2

24
snippets/RPNSolver.md Normal file
View File

@ -0,0 +1,24 @@
### RPNSolver
Solves the given reverse polish notation
```js
const RPNSolver = RPN => {
const isNumeric = str => !isNaN(parseFloat(str)) && isFinite(str);
const isOperator = str => ['*','-','+','/','**'].includes(str)
let stack = [];
let solve = RPN.replace(/\^/g,'**').split(/\s+/g);
solve.forEach(symbol => {
isNumeric(symbol) ? stack.push(symbol) :
isOperator(symbol) ?
(a = stack.pop(),
b = stack.pop(),
stack.push(eval(a + symbol + b))) : Console.log('Wrong RPN')
}
)
return stack.pop()
}
```
```js
```