i recently start a calculator project with react.
I create the project and it works fine but i just wanna add a new feature to it.
i wanna when i click on a operation symbol (like "+", "-", "*", "/") if i click one more time and the operation that exist before that be the same (for example 1234+) when i click on "+" or "-" my code don’t add it to the code and replace it with the before operation and also do that to "/" and "*"
I also attach the repository link so you can see my calculator source code by yourself. the repository of project source code
>Solution :
On your handleClick function simply check if the current character is an operator symbol (e.g: ‘+’,’-‘,’*’,’/’) and the last character in the current result string is also an operator symbol. If they are both operator symbols simply do the following:
const handleClick = (e) => {
if (result.length > 0 && (result[result.length - 1] === '+' || result[result.length - 1] === '-' || result[result.length - 1] === '*' || result[result.length - 1] === '/') && (e.target.name === '+' || e.target.name === '-' || e.target.name === '*' || e.target.name === '/')) {
const newRes = result.slice(0, result.length - 1).concat(e.target.name);
setResult(newRes);
} else {
setResult(result.concat(e.target.name));
}
}