Handling the calculation result
→ Click here to see the state of the app after completing this step.
→ Click here to see the changes we'll make in this step in GitHub.
Finally, let's calculate something with our app!
For that we need to extend our calculator-state to also store the result. If the result is not an empty string, we'll show it in the calcuator display by also adjusting the display selector.
3const calculatorState = gg.state( 4 { 5 firstNumber: "", 6 operator: "", 7 secondNumber: "",+8 result: "", 9 }, 10 { 11 display: (value) =>-[value.firstNumber, value.operator, value.secondNumber].join(" "),+12 [+13 value.firstNumber,+14 value.operator,+15 value.secondNumber,+16 value.result ? "=" : "",+17 value.result,+18 ].join(" "), 19 }, 20);
After our refactoring in the previous step, everything that is left is to adjust the set-state-handler! The button that we want to handle is of course the = button.
In order to be able to calculate the result the two numbers and the operator have to be defined. If that condition is true, then we can parse the two numbers as floating-point-numbers and execute the calculation based on the chosen operator.
69 }+70 case "=": {+71 if (+72 value.firstNumber &&+73 value.firstNumber !== "." &&+74 value.operator &&+75 value.secondNumber &&+76 value.secondNumber !== "."+77 ) {+78 const parsedFirstNumber = parseFloat(value.firstNumber);+79 const parsedSecondNumber = parseFloat(value.secondNumber);+80 switch (value.operator) {+81 case "+":+82 value.result = (+83 parsedFirstNumber + parsedSecondNumber+84 ).toString();+85 break;+86 case "-":+87 value.result = (+88 parsedFirstNumber - parsedSecondNumber+89 ).toString();+90 break;+91 case "×":+92 value.result = (+93 parsedFirstNumber * parsedSecondNumber+94 ).toString();+95 break;+96 case "÷":+97 value.result = (+98 parsedFirstNumber / parsedSecondNumber+99 ).toString();+100 break;+101 }+102 }+103 break;+104 } 105 } 106 return value;
Once there is a result, we don't want to prevent the user from doing anything else for now. In particular he should not be able to enter any more digits. Let's return early in our switch statement in for all other buttons.
38 case "9": {+39 if (value.result) {+40 break;+41 } 42 const number = value.operator ? "secondNumber" : "firstNumber"; ⋮ 46 case "0": {+47 if (value.result) {+48 break;+49 } 50 const number = value.operator ? "secondNumber" : "firstNumber"; ⋮ 56 case ".": {+57 if (value.result) {+58 break;+59 } 60 const number = value.operator ? "secondNumber" : "firstNumber"; ⋮ 69 case "÷": {+70 if (value.result) {+71 break;+72 } 73 if (
We're almost done! Only things left are the calculator controls.