Skip to content

Instantly share code, notes, and snippets.

@coderjonny
Last active July 1, 2019 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coderjonny/ccda6377ad3df04b1bf375f28c9f3f95 to your computer and use it in GitHub Desktop.
Save coderjonny/ccda6377ad3df04b1bf375f28c9f3f95 to your computer and use it in GitHub Desktop.
rpn calculator CLI tool in js
// This function would be used for the CLI program for a RPN calculator
// This assumes that variable stdout is the last value that was stored by the CLI
var rpn_calc = (inputs) => {
const stack = [];
// pseudocode: check the last value for stdout
// stdout is the last stored value in standard out
if (typeof parseInt(stdout) === 'number' ) {
stack.push(parseInt(stdout))
}
// split the input into an array
const inputsArr = inputs.trim().split(' ')
inputsArr.forEach( input => {
switch (input) {
case '+':
stack.push(stack.pop() + stack.pop());
break
case '-':
stack.push(-stack.pop() + stack.pop());
break;
case '*':
stack.push(stack.pop() * stack.pop());
break;
case '/':
stack.push((1 / stack.pop() * stack.pop()));
break;
default:
stack.push(parseInt(input));
break;
}
});
// return last item in the stack
if (parseInt(stack[stack.length - 1]) === 'NaN') {
return 'Error'
} else {
return stack[stack.length - 1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment