diff --git a/snippets/RPNSolver.md b/snippets/RPNSolver.md new file mode 100644 index 000000000..2cfb59be5 --- /dev/null +++ b/snippets/RPNSolver.md @@ -0,0 +1,24 @@ +### RPNSolver + +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 !== '')] + 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 { throw `${symbol} is not a recognized symbol` } + } +) + if(stack.length === 1) return stack.pop() + else throw `${RPN} is not a proper RPN. Please check it and try again` +} +``` + +```js + +``` diff --git a/snippets/infixToPostFix.md b/snippets/infixToPostFix.md index 3fd859e37..b05496977 100644 --- a/snippets/infixToPostFix.md +++ b/snippets/infixToPostFix.md @@ -1,4 +1,9 @@ -const infix = expr => { +### infixToPostfix + +Works perfectly! + +```js +const infixToPostfix = expr => { let rpn = '' let solve = expr.replace(/\^/g,'**').match(/([0-9]+|[\+\(\)\/\-]|\*+)/g).filter(el => !/\s+/.test(el) && el !== '') let stack = [] @@ -22,3 +27,7 @@ const infix = expr => { } return rpn } +``` +```js + +``` diff --git a/snippets/postfixToInfix.md b/snippets/postfixToInfix.md index c54bd44f0..19e191c6b 100644 --- a/snippets/postfixToInfix.md +++ b/snippets/postfixToInfix.md @@ -1,4 +1,9 @@ -const postFix = RPN => { +### postfixToInfix + + This one has few errors and does not work properply + +```js +const postfixToInfix = RPN => { let convert = RPN.replace(/\^/g,'**').split(/\s+/g).filter(el => !/\s+/.test(el) && el !== '') let stack = [] let result = [] @@ -27,3 +32,7 @@ const postFix = RPN => { if(result.length === 1) return result.pop() else throw `${RPN} is not a correct RPN` } +``` +```js + +```