Hey everyone- I am wrapping up a rough draft of my React Calculator and I am failing the consecutive operator test…
I wrote my code such that you cant enter consecutive operators, it just will ignore the click event if you try to enter a second operator without first hitting another number. This seems more elegant than parsing whatever is entered. Would there be a way to get credit for completing this project if everything else checks out?
A snipnet of the code that controls this logic:
const handleOperator = (operator) => {
// only allow an operator to be entered if a number has been entered
if(this.state.result !== 0 && this.state.operator === false){
this.setState(prevState => ({ result: prevState.result + operator }));
this.setState({ operator: true });
}
};
const handleClick = (event) => {
// console.log(`clicked ${event.display}`);
const { display, id } = event;
switch (id){
case 'clear':
// reset display
clearDisplay();
break;
case 'divide':
case 'multiply':
case 'add':
case 'subtract':
// insert the correct operator into calculator expression
const operator = display;
handleOperator(operator);
this.setState({ decimal: false });
break;
case 'decimal':
// handle decimals
if(this.state.decimal === false){
this.setState(prevState => ({ result: prevState.result + display }));
this.setState({ decimal:true });
}
break;
case 'equals':
// handle solving input
const result = calculateResult();
console.log(String(result));
this.setState({result:result});
break;
default:
// handle number input
// if display has "0", rewrite initial number
if (this.state.result == 0) {
this.setState({ result: display });
} else {
this.setState(prevState => ({ result: prevState.result + display }));
this.setState({ operator:false });
}
}
My full code is on github
A running preview can also been seen here