Last active
July 1, 2019 21:48
-
-
Save coderjonny/ccda6377ad3df04b1bf375f28c9f3f95 to your computer and use it in GitHub Desktop.
rpn calculator CLI tool in js
This file contains 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
// 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