(4 minute read)
These were my requirements:
- It must be quick to load.
Evaluating arithmetic expresssions
I decided to model the functioning of my calculator on the stock one which came with my HTC Hero Android phone. Unlike most ordinary calculators this handily displays the full set of operations that you've punched in:
What this meant was my calculator had to be able to parse such an input string (which is using Infix notation in mathematical terms), convert it to Postfix (also known as Reverse Polish) notation - a format which makes it easier to evaluate algorithmically, notifying the user if there were any errors in the input. So for example, the following input expression in Infix notation:
would look as follows in Postfix notation:
The difference between the two notations is simple. In Infix the operator (e.g. ) is written between its two operands. In Postfix the operator is written after its two operands. The benefit of Postfix is that the operators are in order of precedence according to BODMAS rules and a simple Stack-based algorithm can be used to evaluate the final answer.
Making the most of the browser window
I admit that this isn't as nice as doing it all in CSS, as it's slightly slower than letting the browser do all this work. I'm still investigating a better way of doing this,
especially since the calculator buttons currently overflow to the right in Mobile Safari - sorry, iPhone and iPod Touch users (if you have any suggestions as to why this happens please let me know!) Update: now looks ok on iOS devices running 4.2.
When you turn the phone into landscape mode there is currently space on either side of the calculator button pad. In future I plan to add other buttons here (e.g. the ones you usually get with scientific calculators) so that you can easily switch between simple and 'advanced' mode by turning your phone.
The full source code is available in the single HTML file on the site and it's licensed under GPL 3. And apologies for the uninspiring domain name!
The calculator width issue on iPhones and iPod Touches mentioned above. Update: Seems to be ok now in iOS 4.2.
Another issue I've noticed on Android is that you can't press the buttons in rapid succession because the browser assumes you're trying to zoom in. I'm already using meta tags to markup the the page as mobile-friendly but it would be nice be able to disable the zoom-in mechanism on mobile browsers.