Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save xadim/992174018549456fff8fe10c67780f74 to your computer and use it in GitHub Desktop.

Select an option

Save xadim/992174018549456fff8fe10c67780f74 to your computer and use it in GitHub Desktop.
/**
*
* @param str
* @returns
*/
function reversePolish(str) {
str = str.split(" "), result = [];
if (str === "" || str === null) return;
let haystack = str.map((i) => {
return Number(i) ? Number(i) : i;
});
const operators = {
"+": (a, b) => a + b,
"-": (a, b) => a - b,
"*": (a, b) => a * b,
"/": (a, b) => a / b,
};
haystack.forEach(op => {
result.push (
operators[op]
? operators[op](...result.splice(-2))
: op
)
});
return result[0];
}
console.log(reversePolish("3 4 + 2 * 1 +"));
@xadim
Copy link
Author

xadim commented Dec 19, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment