Created
January 23, 2017 20:13
-
-
Save jasonwaters/e1486c73b0facea3c5d31f8bfca1f6ba to your computer and use it in GitHub Desktop.
reverse polish notation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // a script that processes arithmetic in reverse polish notation | |
| //https://en.wikipedia.org/wiki/Reverse_Polish_notation | |
| const operate = { | |
| '+': (a,b) => a+b, | |
| '-': (a,b) => a-b, | |
| '*': (a,b) => a*b, | |
| '/': (a,b) => a/b, | |
| }; | |
| const OPERATORS = Object.keys(operate); | |
| function reversePolish(str) { | |
| let nums = []; | |
| let parts = str.split(' '); | |
| for(let part of parts) { | |
| if(OPERATORS.includes(part)) { | |
| let operandA = nums.pop(); | |
| let operandB = nums.pop(); | |
| nums.push(operate[part].call(null, operandB, operandA)); | |
| }else { | |
| nums.push(parseInt(part, 10)); //number | |
| } | |
| } | |
| return parseInt(nums[0], 10); | |
| } | |
| console.log(reversePolish("5 3 * 2 +")); //17 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment