1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2024-12-08 00:45:29 +01:00

feat: add reverse-polish-notation javascript solution

This commit is contained in:
Divlo 2020-09-29 13:04:50 +00:00
parent 9999d34d9a
commit 8e93bfbff6
3 changed files with 38 additions and 1 deletions

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
node_modules
.vscode
.theia

View File

@ -0,0 +1,5 @@
# javascript-solution - reverse-polish-notation
Programming language : JavaScript
Created by [@Divlo](https://github.com/Divlo) on 29 September 2020.

View File

@ -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