From bb48e5cf6d5b6b202e43a48bcabab18b54c2789c Mon Sep 17 00:00:00 2001 From: Andrzej Stepien Date: Wed, 5 Jul 2023 23:23:46 +0200 Subject: [PATCH] a,b calculations now working, but not a,b,c --- src/Components/Button.js | 2 +- src/Components/Calculator.js | 37 +++++++++++++++++++++++++-------- src/Components/KeyPad.js | 40 ++++++++++++++++++++++++------------ 3 files changed, 56 insertions(+), 23 deletions(-) diff --git a/src/Components/Button.js b/src/Components/Button.js index f8f0462..86ba0f9 100644 --- a/src/Components/Button.js +++ b/src/Components/Button.js @@ -1,6 +1,6 @@ export default function Button(props){ return( - + ) } \ No newline at end of file diff --git a/src/Components/Calculator.js b/src/Components/Calculator.js index ac6c629..f70addc 100644 --- a/src/Components/Calculator.js +++ b/src/Components/Calculator.js @@ -2,12 +2,20 @@ import { useState } from "react"; import KeyPad from "./KeyPad"; export default function Calculator(props){ - const [main,setMain] = useState(0) - const [memory,setMemory] = useState(0) + const [main,setMain] = useState("0") + const [memory,setMemory] = useState("0") const [operation,setOperation] = useState("") const map = { - conc:(numberString)=>{setMain(prev=>prev+numberString)}, + conc:(numberString)=>{ + if(main[0]==="0"){ + console.log("STARTS WITH ZERO") + setMain(prev=>prev.slice(1)+numberString) + }else{ + setMain(prev=>prev+numberString) + } + + }, zero:function(){this.conc("0")}, one:function(){this.conc("1")}, @@ -20,7 +28,7 @@ export default function Calculator(props){ eight:function(){this.conc("8")}, nine:function(){this.conc("9")}, decimal:function(){ - if(!/./g.test(main)){ + if(!/\./g.test(main)){ this.conc(".") } }, @@ -40,9 +48,20 @@ export default function Calculator(props){ add:(a,b)=>{return a+b}, subtract:(a,b)=>{return a-b}, multiply:(a,b)=>{return a*b}, - divide:(a,b)=>{return a/b}, - }, - equals:()=>{setMain(prev=>{this.operations[operation](prev,memory)})} + divide:(a,b)=>{return b/a}, + }, + + clear:()=>{ + setMain("0") + setMemory("0") + setOperation("") + }, + equals:function(){ + setMain(prev=>{ + return this.operations[operation](parseInt(prev),parseInt(memory)).toString() + }) + setOperation("") + } } function handleInput(content){ @@ -53,9 +72,9 @@ export default function Calculator(props){ return( <> -
+

{memory}

-

{main}

+

{main}

{operation}

diff --git a/src/Components/KeyPad.js b/src/Components/KeyPad.js index e723b56..ebd24b2 100644 --- a/src/Components/KeyPad.js +++ b/src/Components/KeyPad.js @@ -22,23 +22,37 @@ export default function NumPad(props){ } + const functionMap = { + clear:"C", + equals:"=" + } + function buildButtons(map){ + return Object.keys(map).map((e,i)=>{ + return( + + ) + }) + } - const numPad = Object.keys(numberMap).map((e,i)=>{ - return( - - ) - }) return( -
- {numPad} +
+
+ {buildButtons(numberMap)} +
+
+ {buildButtons(operatorMap)} +
+
+ {buildButtons(functionMap)} +
) } \ No newline at end of file