I think I want to try a different approach with the decimal thing. I only want to enable it if:
a) the current value begins with a 0 (or any number) and is not followed by an operator,
b) if the preceding inputs are both an operator and a number,
c) if there´s no decimal present.
How could I do that? I know there´s the disabled prop, but how could I use it?
const button1 = [{number: 'one', value: '1'},{number: 'two', value: '2'},{number: 'three', value: '3'},{number: 'divide', value: '/'}];
const button2 = [{number: 'four', value: '4'},{number: 'five', value: '5'},{number: 'six', value: '6'},{number: 'add', value: '+'}];
const button3 = [{number: 'seven', value: '7'},{number: 'eight', value: '8'},{number: 'nine', value: '9'},{number: 'subtract', value: '-'}];
const button4 = [{number: 'zero', value: '0'},{number: 'equals', value: '='},{number: 'multiply', value: '*'}];
class Calculator extends Component {
constructor(props) {
super(props);
this.state = { value: "0"};
this.handleClick = this.handleClick.bind(this);
this.handleDecimal=this.handleDecimal.bind(this);
}
handleClick(evt) {
const id = evt.target.id;
const result = evt.target.value;
switch(id) {
case 'clear':
this.setState({ value: "0"});
break;
case 'equals':
this.setState(prevState => ({
value: math.eval(this.state.value)
}));
break;
default: this.setState(prevState => ({
value: `${prevState.value}${result}`
.replace(/([/+\-/*=])([/+\-*=])/g, "$2")
.replace(/^0+(?=[1-9])/, "")
.replace(/^0+(?=\.)/, "0")
.replace(/^0+\B/, "")
.replace(/\.+/g,".")
}));
}
}
handleDecimal(evt){
const result = evt.target.value;
let value = this.state.value;
let regex=/([-+*/][0-9])/;
let regex2=/([0][-+*/])/;
if(value.indexOf(".")===-1){
this.setState(prevState => ({
value: this.state.value + result
}))}
else if(value.match(regex2)!==null){
this.setState(prevState => ({
value: this.state.value
}))
}
else if(regex.test(value)===true){
this.setState(prevState => ({
value: this.state.value + result
}))}
}
render() {
return(
<div id="container">
<Display value={this.state.value} />
<div>
{button1.map(el => <Button onClick={this.handleClick} key={el.index} id={el.number} value={el.value} />)}
</div>
<div>
{button2.map(el => <Button onClick={this.handleClick} key={el.index} id={el.number} value={el.value} />)}
</div>
<div>
{button3.map(el => <Button onClick={this.handleClick} key={el.index} id={el.number} value={el.value} />)}
</div>
<div>
{button4.map(el => <Button onClick={this.handleClick} key={el.index} id={el.number} value={el.value} />)}
<Button onClick={this.handleDecimal} id="decimal" value={"."} />
</div>
<div>
<Button onClick={this.handleClick} id="clear" value={'clear'} />
</div>
</div>
)
}
}