Skip to content

Instantly share code, notes, and snippets.

@jasonwaters
Created January 23, 2017 20:13
Show Gist options
  • Select an option

  • Save jasonwaters/e1486c73b0facea3c5d31f8bfca1f6ba to your computer and use it in GitHub Desktop.

Select an option

Save jasonwaters/e1486c73b0facea3c5d31f8bfca1f6ba to your computer and use it in GitHub Desktop.
reverse polish notation
// 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