I have been on this problem for a while now and I think I have found the regex that will sanitize the input so it can’t have any weird cases like 2 decimals in a number. But now when I try to think of an implementation to let the user replace their previous operation I can’t get it to work and the number of my passing tests go down.
My code so far
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
// componentWillMount()
// componentDidMount()
// componentWillReceiveProps() //good for comparison
// shouldComponentUpdate()// must return a boolean
// componentWillUpdate()
// componentDidUpdate()
// componentWillUnmount()
class Calculator extends React.Component {
constructor(props) {
super(props);
this.state = {
inputString: ""
};
this.handleInput = this.handleInput.bind(this);
this.handleClear = this.handleClear.bind(this);
this.handleEquals = this.handleEquals.bind(this);
}
handleInput(event) {
this.setState({
inputString: this.state.inputString + event.target.value
});
}
handleClear(event) {
this.setState({
inputString: ""
});
}
handleEquals() {
this.setState({
inputString: eval(this.state.inputString)
});
}
shouldComponentUpdate() {
let regex = /(\d*\.\d*\.)|\.{2}|\+{2}|\-{2}|^[*\/]|^00|(?<=\b)0{2}/g;
return !regex.test(this.state.inputString);
}
render() {
return (
<div className="Calc">
<button id="equals" value="=" onClick={this.handleEquals}>
=
</button>
<button id="zero" onClick={this.handleInput} value="0">
0
</button>
<button id="one" onClick={this.handleInput} value="1">
1
</button>
<button id="two" onClick={this.handleInput} value="2">
2
</button>
<button id="three" onClick={this.handleInput} value="3">
3
</button>
<button id="four" onClick={this.handleInput} value="4">
4
</button>
<button id="five" onClick={this.handleInput} value="5">
5
</button>
<button id="six" onClick={this.handleInput} value="6">
6
</button>
<button id="seven" onClick={this.handleInput} value="7">
7
</button>
<button id="eight" onClick={this.handleInput} value="8">
8
</button>
<button id="nine" onClick={this.handleInput} value="9">
9
</button>
<button id="add" value="+" onClick={this.handleInput}>
+
</button>
<button id="subtract" value="-" onClick={this.handleInput}>
-
</button>
<button id="divide" value="/" onClick={this.handleInput}>
/
</button>
<button id="multiply" value="*" onClick={this.handleInput}>
*
</button>
<button id="decimal" value="." onClick={this.handleInput}>
.
</button>
<button id="clear" onClick={this.handleClear}>
AC
</button>
<div id="display">
{this.state.inputString === "" ? 0 : this.state.inputString}
</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Calculator />, rootElement);
Does anyone know how I can go about replacing operators? I’m trying to think of a solution that uses the replace method but can’t see a solution. Thank you for reading.