calculator/src/Components/Calculator.js

48 lines
1.2 KiB
JavaScript
Raw Normal View History

2023-07-04 11:15:57 +00:00
import { useState } from "react";
import NumPad from "./NumPad";
import Operators from "./Operators";
export default function Calculator(props){
2023-07-04 15:09:09 +00:00
const [main,setMain] = useState(0)
2023-07-04 11:15:57 +00:00
const [memory,setMemory] = useState(0)
const [operation,setOperation] = useState("")
2023-07-04 11:15:57 +00:00
function handleInput(content){
2023-07-04 15:09:09 +00:00
const operations = {
"+":(a,b)=>{return a+b},
"-":(a,b)=>{return a-b},
"X":(a,b)=>{return a*b},
"/":(a,b)=>{return a/b},
}
2023-07-04 15:09:09 +00:00
2023-07-04 11:15:57 +00:00
if(typeof content === "number" ){
2023-07-04 15:09:09 +00:00
setMain(prev=>{return prev.toString()+content.toString()})
2023-07-04 15:13:24 +00:00
}else if(content == "."){
//HANDLE DECIMAL WITH REGEX
}else if(operations[content]){
2023-07-04 15:09:09 +00:00
setMemory(prev=>{operations[content](prev,main)})
setMain(0)
2023-07-04 11:15:57 +00:00
setOperation(content)
2023-07-04 15:13:24 +00:00
}else{
throw new Error("Parameter is not a number, '.' or operator.")
2023-07-04 11:15:57 +00:00
}
}
return(
<>
<div id="display">
<p id="memory">{memory}</p>
2023-07-04 15:09:09 +00:00
<p id="main">{main}</p>
2023-07-04 11:15:57 +00:00
<p id="operation">{operation}</p>
</div>
2023-07-04 15:15:29 +00:00
<NumPad handlemain={handleInput}/>
<Operators handlemain={handleInput}/>
2023-07-04 11:15:57 +00:00
</>
)
}