Can't figure out the "no leading zeros" user-story

Hi, I’m having a lot of trouble figuring out how to prevent a number from having trailing zeros. This is what I have so far in the default case of the switch statement in my handleClick (it’s the first if statement):

      default:
        if(this.state.evaluation.join("").match(/^00/)){
          break;
        };
        
        
        if(isNaN(value) && isNaN(this.state.evaluation[this.state.evaluation.length-1])) {
          break;
        };
        
        this.setState({evaluation: [...this.state.evaluation, value]}, () => {
          this.props.setEvaluation(this.state.evaluation.join(""));
        });
        break;
    }

By using .match(), it causes the input to “freeze up”. In other words, if I begin a calculation with two zeros, not only can I not type more zeros but I simply can’t continue the calculation with hitting the clear button and starting over. What could I be doing wrong here?

Here’s the whole project on codepen: https://codepen.io/Dusch4593/pen/RwbgGer

In your code, the state is set after the switch statement, so it’s always one behind the current value.

To catch the leading zero in your case, you need to join the current state with the incoming value and use that to decide what to do.

this.state.evaluation.join()+value

So I went ahead and joined the current state with the incoming value outside the switch statement:

  handleClick = (event) => {
    let value = event.target.getAttribute("data-value");
    this.setState({
      evaluation: this.state.evaluation.join('')+value
    })
    switch(value)
    {

I then added a case clause inside the switch statement for when the user types “0” that tests whether it is the first character in the string:

      case "0":
        if(this.state.evaluation.join("").match(/^0/)){
          this.setState({
            evaluation: []
          },() => {
            this.props.setEvaluation(this.state.evaluation)
          })
          break;
        }

This is definitely preventing leading zeros from happening (if I try to type a second zero, it state of the evaluation is cleared and I have to start over. But it does the job! Thank you!