From 8e93bfbff682af7a3de99ed078bbe5e1af765f79 Mon Sep 17 00:00:00 2001 From: Divlo Date: Tue, 29 Sep 2020 13:04:50 +0000 Subject: [PATCH] feat: add reverse-polish-notation javascript solution --- .gitignore | 3 +- .../solutions/javascript-solution/README.md | 5 +++ .../solutions/javascript-solution/solution.js | 31 +++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 challenges/reverse-polish-notation/solutions/javascript-solution/README.md create mode 100644 challenges/reverse-polish-notation/solutions/javascript-solution/solution.js diff --git a/.gitignore b/.gitignore index 55371e5..13fe3b2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ node_modules -.vscode \ No newline at end of file +.vscode +.theia \ No newline at end of file diff --git a/challenges/reverse-polish-notation/solutions/javascript-solution/README.md b/challenges/reverse-polish-notation/solutions/javascript-solution/README.md new file mode 100644 index 0000000..5a1da1d --- /dev/null +++ b/challenges/reverse-polish-notation/solutions/javascript-solution/README.md @@ -0,0 +1,5 @@ +# javascript-solution - reverse-polish-notation + +Programming language : JavaScript + +Created by [@Divlo](https://github.com/Divlo) on 29 September 2020. diff --git a/challenges/reverse-polish-notation/solutions/javascript-solution/solution.js b/challenges/reverse-polish-notation/solutions/javascript-solution/solution.js new file mode 100644 index 0000000..4e62170 --- /dev/null +++ b/challenges/reverse-polish-notation/solutions/javascript-solution/solution.js @@ -0,0 +1,31 @@ +const operations = { + '+': (n1, n2) => n1 + n2, + '-': (n1, n2) => n1 - n2, + '*': (n1, n2) => n1 * n2, + '/': (n1, n2) => n1 / n2 +} + +function solution(value) { + if (value.length === 0) { + return 0 + } + + const stack = [] + const values = value.split(' ') + values.forEach((value) => { + const number = Number(value) + if (!isNaN(number)) { + stack.push(number) + } else if (operations.hasOwnProperty(value)) { + const number1 = stack.pop() + const number2 = stack.pop() + const operation = operations[value] + const result = operation(number2, number1) + stack.push(result) + } + }) + + return stack.pop() +} + +module.exports = solution