Created
September 5, 2012 22:21
-
-
Save rvbsanjose/3646245 to your computer and use it in GitHub Desktop.
RPN Calculator in JavaScript
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
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you use eval(), this code could be like that: