DEV Community

Matthew Palmer
Matthew Palmer

Posted on

React Calculator (Oh god...)

Introduction

Calculators are all fun and games until you start thinking about all the ridiculous edge cases. Travel down this rabbit hole with me...

Operators & Parenthesis

Let's start off with talking about why these edge cases are so important. Let's assume you have an equation: 34+45*(34

Now, when you try to evaluate this... What do you think happens? It's a no brainer, you're gonna get an error. How do we fix it then? End users are creative, oblivious, and they definitely wont use our calculator in the exact way we created it to be used. At the very least, they wont all follow a logical pattern. So, one method you might go with is something along the lines of eval(result + ")"). Awesome, that solves the problem!

Well... it solves that VERY NARROW problem. What happens when they type 34+45*(7)*(. Chances are, your fix accounted for whether ( and ) exist. They both exist now, and we've run into the same problem as before, but now it's advanced. So we now check to see if the very END of our equation includes a ( or with a number like (4. Depending on the case, we either remove the ( or add a ).

Operators (+, -, *, /)

Operators are a bit easier to handle. We basically check if the most recent item in the equation is an operator. If it is, either we replace it or keep it the same (if we chose the exact same operator again).

This is how I handled it:

const handleOperator = e => {
        let newResult = result.split("");
        let checker = newResult[newResult.length - 1]

        // Checks if an operator already exists at the end of the operation
        // If it does, replace it with the one that was clicked
        if(checker === "+" || checker === "-" || checker === "*" || checker === "/") {
            newResult.pop()
        }
        const joiner = newResult.join("")
        setResult(joiner + e.target.value)
    }
Enter fullscreen mode Exit fullscreen mode

Conclusion

Okay, today this post was a very quick one. But I believe it highlights the complexity in simplicity. Once of the easiest projects we've ever worked on as developers has been a calculator. However, I strongly believe we underestimate just how complex calculators can be. It's not as easy as mapping buttons and having a great 'ol time. There are so many use-cases that need to be accounted for, and I've likely not truly covered them all today. If there is anyone else out there reading this and going through the same thing, I hope this post provides some perspective. It's the result of hours of headache and burnout trying to think things through.

Happy Tuesday, everyone!

Oldest comments (0)