I created a grid of styled Buttons that have an onclick function: handleButtonClick
. I also created a few state variables:
total
- the total of the calculationsinput
- when the user inputs a new valueoperator
- the operator that is selectedselectedKey
- to tell when a key has been pressed so we can highlight itdisplay
- the string value that is shown to the user on the calculator
from here I created functions to break the code up into the functionality we need:
handleButtonClick
:- this function determines where we move next: to handle the key change, clear the values, calculate a result, set a negative number, or handle percentages
handleKeyChange
:- this function sets the string value that appears as the total on the calculator. It formats the string properly for the UI and handles concatenation of srings (how I kept track of which value was the user's input vs. the total was by intially setting the
input
variable tonull
and the total tozero
. I would know that if theinput
wasnull
, then we have not entered a second number to calculate yet)
- this function sets the string value that appears as the total on the calculator. It formats the string properly for the UI and handles concatenation of srings (how I kept track of which value was the user's input vs. the total was by intially setting the
calculateNewValue
:- this function calculates a new total by either adding, subtracting, multiplying or dividing the
total
and theinput
- this function calculates a new total by either adding, subtracting, multiplying or dividing the
handleNegativeNumber
:- this function handles when the
+/-
key is clicked. it will insert a "-" char to the display string (or remove it if it already exists) and updates the numeric value as well
- this function handles when the
clearValues
:- this function resets the state when the
AC
key is pressed
- this function resets the state when the
handlePercentage
:- this function either divides the total by 100 if no
input
is present, or is calculates the percentage of the total that has been entered
- this function either divides the total by 100 if no