49 lines
1.5 KiB
JavaScript
49 lines
1.5 KiB
JavaScript
|
import React from 'react';
|
||
|
import './Calculator.css';
|
||
|
|
||
|
export default class Calculator extends React.Component {
|
||
|
constructor(props) {
|
||
|
super(props);
|
||
|
this.state = {
|
||
|
a: "",
|
||
|
b: "",
|
||
|
operator: "ADD"
|
||
|
}
|
||
|
}
|
||
|
|
||
|
calcResult({a, operator, b}) {
|
||
|
a = parseFloat(a);
|
||
|
b = parseFloat(b);
|
||
|
if(isNaN(a) || isNaN(b) || !operator) {
|
||
|
return "";
|
||
|
}
|
||
|
switch(operator) {
|
||
|
case "ADD":
|
||
|
return a + b;
|
||
|
case "SUBTRACT":
|
||
|
return a - b;
|
||
|
case "MULTIPLY":
|
||
|
return a * b;
|
||
|
case "DIVIDE":
|
||
|
return a / b;
|
||
|
}
|
||
|
return "";
|
||
|
}
|
||
|
|
||
|
render() {
|
||
|
return <div className="card mt-3"><div className="card-body">
|
||
|
<p>This interviewer requested that I make a component that allowed a user
|
||
|
to input two numbers and select an operator and get a result.</p>
|
||
|
<input className="calc-number-input" onChange={e => this.setState({a: e.target.value})} />
|
||
|
<select className="calc-operator-input" onChange={e => this.setState({operator: e.target.value})}>
|
||
|
<option value="ADD">{String.fromCharCode(0x2B)}</option>
|
||
|
<option value="SUBTRACT">{String.fromCharCode(0x2D)}</option>
|
||
|
<option value="MULTIPLY">{String.fromCharCode(0xD7)}</option>
|
||
|
<option value="DIVIDE">{String.fromCharCode(0xF7)}</option>
|
||
|
</select>
|
||
|
<input className="calc-number-input" onChange={e => this.setState({b: e.target.value})} />
|
||
|
= <span className="calc-answer">{this.calcResult(this.state)}</span>
|
||
|
</div></div>;
|
||
|
}
|
||
|
}
|