From 72be2583733891f71f0eab7cea8eecfbb6f104b7 Mon Sep 17 00:00:00 2001 From: RealPeha Date: Sat, 3 Oct 2020 16:12:23 +0300 Subject: [PATCH 1/2] Added ReversePolishNotation --- Maths/ReversePolishNotation.js | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Maths/ReversePolishNotation.js diff --git a/Maths/ReversePolishNotation.js b/Maths/ReversePolishNotation.js new file mode 100644 index 0000000000..e949c94419 --- /dev/null +++ b/Maths/ReversePolishNotation.js @@ -0,0 +1,33 @@ +function calcRPN (expression) { + const operators = { + '+': (a, b) => a + b, + '-': (a, b) => a - b, + '*': (a, b) => a * b, + '/': (a, b) => b / a + } + + const tokens = expression.split(' ') + + const stack = [] + + tokens.forEach(token => { + const operator = operators[token] + + if (typeof operator === 'function') { + const a = stack.pop() + const b = stack.pop() + + const result = operator(a, b) + + stack.push(result) + } else { + stack.push(parseFloat(token)) + } + }) + + return stack.pop() +} + +console.log(calcRPN('2 2 2 * +') === 6) +console.log(calcRPN('2 2 + 2 *') === 8) +console.log(calcRPN('6 9 7 + 2 / + 3 *') === 42) From 30ab9d4990ca25c01a3d124d47f698f07b6f3c2f Mon Sep 17 00:00:00 2001 From: RealPeha Date: Sat, 3 Oct 2020 16:22:48 +0300 Subject: [PATCH 2/2] Added link to Wikipedia --- Maths/ReversePolishNotation.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Maths/ReversePolishNotation.js b/Maths/ReversePolishNotation.js index e949c94419..ef31300a9d 100644 --- a/Maths/ReversePolishNotation.js +++ b/Maths/ReversePolishNotation.js @@ -1,3 +1,5 @@ +// Wikipedia: https://en.wikipedia.org/wiki/Reverse_Polish_notation + function calcRPN (expression) { const operators = { '+': (a, b) => a + b,