Created
December 21, 2010 06:42
-
-
Save masonicboom/749586 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| <div><script type="text/javascript"> | |
| function thoughtful_evaluate(expression) { | |
| var x = ''; | |
| var chunks = expression.split(/\s/); | |
| for (i in chunks) { var chunk = chunks[i]; | |
| if (chunk.match(/^[\+\-\/\*]$/) != null) | |
| // this chunk is a single operator | |
| x += chunk; | |
| else | |
| x += eval(chunk); | |
| } | |
| return eval(x); | |
| } | |
| function compute_results() { | |
| var x = document.getElementById('t').value; | |
| if (x.match(/^[1234567890\+\-\/\*\s]*$/) == null) { | |
| alert('invalid expression; only numbers and arithmetic operators are allowed.'); | |
| } | |
| document.getElementById('standard_result').innerHTML = eval(x); | |
| document.getElementById('thoughtful_result').innerHTML = thoughtful_evaluate(x); | |
| }</script>Type an arithmetic expression in the box below and then click "evaluate". <br /><input value="5+6 * 2" id="t" /><button onclick="compute_results();">evaluate</button> <br />Below, you see the results of evaluating the above expression under two different schemes: <a href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Operator_Precedence#Table">JavaScript's standard order of operations</a> and my "thoughtful" order of operations which groups expressions based on whitespace. <table><tbody> <tr> <td><b>standard</b></td> <td id="standard_result"> </td> </tr> <tr> <td><b>thoughtful</b></td> <td id="thoughtful_result"> </td> </tr> </tbody></table> </div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment