Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how I can write this condition in javascript(Reactjs)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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));
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading