Skip to content

Instantly share code, notes, and snippets.

@rvbsanjose
Created September 5, 2012 22:21
Show Gist options
  • Save rvbsanjose/3646245 to your computer and use it in GitHub Desktop.
Save rvbsanjose/3646245 to your computer and use it in GitHub Desktop.
RPN Calculator in JavaScript
<html>
<head>
<title>RPN Calculator</title>
<style type="text/css">
body {
color: white;
background-color: blue;
font-weight: bold;
font-size: 24px;
text-align: center;
margin-top: 200px;
}
</style>
<script type="text/javascript">
function evaluate() {
var input = prompt("Please enter your input string\n\nExamples of input strings:\n\n\t1. 10 4 5 + *\n\t2. 10 4 5 + * 2 +\n\t3. 10 8 *");
var values = input.split(" ");
var array = new Array();
for (i in values) {
if (values[i] != "+" && values[i] != "*" && values[i] != "-" && values[i] != "/") {
array.push(parseInt(values[i]));
} else {
var operator = values[i];
var val2 = array.pop();
var val1 = array.pop();
switch (operator) {
case "+":
array.push(eval("val1 + val2"));
break;
case "*":
array.push(eval("val1 * val2"));
break;
case "-":
array.push(eval("val1 - val2"));
break;
case "/":
array.push(eval("val1 / val2"));
break;
}
}
}
if (input == "" || input == null) {
document.writeln("Oops, based on your input we have nothing to calculate for you!");
} else {
document.writeln("Your RPN calculation is: ");
document.writeln(array + " with a starting input string of: " + input);
}
}
</script>
</head>
<body>
<h2>Online RPN Calculator</h2>
<script type="text/javascript">
evaluate();
</script>
</body>
</html>
@damianc
Copy link

damianc commented Dec 16, 2014

If you use eval(), this code could be like that:

function calc( input ) {
  var formula = input.split( ' ' );
  var ops = [ '+', '*', '-', '/' ];
  [].forEach.call( formula, function( item, index, arr ) {
    if ( ops.indexOf( item ) !== -1 ) {
      formula[index-1] = [ formula[index], formula[index] = formula[index-1] ][0];
    }
  } );
  console.log( eval( formula.join( '' ) ) );
}

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