The hardest part of this project is trying to copy the design of the iOS app. For this, I will use CSS. The structure is very simple: it’s a table of six rows where we place the elements by columns (the buttons and the display).
A calculator should make math operations. I develop six JS functions that resolve most of these common operations:
- Reset. If there is something on the display, it clear it, otherwise it removes the content of temporary and operation variables.
- Add number. Adds a number passed by parameter to the display.
- Operation. Add the operator passed as a parameter to the operation variable and clear the display.
- Resolve. Solves the operation (temp variable [operation] actual value on display).
- Inverse. Multiplies the display value by -1.
- Percentage. Divide the display value by 100.
The variable temporal stores the number that was written on the display just before pressing an operation symbol. The operation variable stores the last operator we have selected to execute the evaluation of the expression when we press the “=” button.
However, there are many things to improve in this code, for example:
- Do many operations in a row without having to press equals key between operations.
- Prevent more than one point from being placed on the display.