Here is the code, I have written comments here to explain what logic I want. I need to pass test no. 11 and 13 in JavaScript Calculator and here is link to full code Calculator Codepen
Calculate(e) {
const changeState = () => {
this.setState({
calcString: (this.state.calcString += e.target.innerHTML),
display: this.state.calcString
});
};
if (e.target.id == "decimal") {
// when decimalCounter is <=1 that data is allowed to be entered in this.state.calcString
if(/[+*\\-]/g.test(this.state.calcString)){
//whenever an operator is found decimal should be allowed to be entered
decimalCounter=0;
console.log("operators found")
} if(/\d+\.\d+/g.test(this.state.calcString)){
//whenever something of type 5.5 is found no more decimal should be allowed until next oprator is found
decimalCounter++;
console.log("d.d pattern found")
}else{
//when simple digits like 5 are entered decimal should be allowed once until something like 5.5 is entered
decimalCounter++;
console.log("in decimal code but no operators here")
}
} else {
//when other buttons are pressed except decimal,they should be allowed to be entered by setting decimalCounter = 0
decimalCounter = 0;
console.log("hey")
}
if (e.target.id == "clear") {
this.setState({
display: "0",
calcString: ""
});
}
if (e.target.id == "equals" && this.state.calcString !== "") {
this.setState({
calcString: eval(this.state.calcString),
display: eval(this.state.calcString)
});
}
if (
this.state.calcString == "" &&
e.target.id !== "clear" &&
e.target.id !== "equals" &&
e.target.id !== "zero"
) {
changeState();
} else if (
this.state.calcString !== "" &&
e.target.id !== "clear" &&
e.target.id !== "equals" &&
decimalCounter <= 1
) {
changeState();
}
}