Hello! My calculator seems to be working but isn’t passing the following:
- User Story #14: Pressing an operator immediately following = should start a new calculation that operates on the result of the previous evaluation.
Would really appreciate any assistance figuring out why. I am using React and Redux.
Calculator Component
class Calculator extends Component {
// Adding click event handler to all button divs, once component has rendered
componentDidMount() {
[...document.querySelectorAll('.operand, .operator, .equals, .clear')]
.forEach(btn => btn.addEventListener('click', this.handleClick.bind(this)));
}
// Passes clicked btn to action creator
handleClick(event) {
this.props.btnClick(event.target.innerText);
}
// CSS grid for layout, Display for result is taken off state
render() {
return (
<div>
<h4>React-Redux Calculator</h4>
<div className='wrapper'>
<div id='display'>{this.props.result}</div>
<div className='clear' id='clear'><button>AC</button></div>
<div className='operator' id='divide'><button>/</button></div>
... more button divs
</div>
<p>Coded by <a href='https://github.com/RicardoL-AFati/fccFrontEnd-calculator'>Ricardo Ledesma</a></p>
</div>
);
}
}
const mapStateToProps = ({ result }) => ({ result });
const mapDispatchToProps = dispath => bindActionCreators({ btnClick }, dispath);
export default connect(mapStateToProps, mapDispatchToProps)(Calculator);
root reducer
const rootReducer = combineReducers({
result: resultReducer,
});
export default rootReducer;
result_reducer - relevant cases
const endsWithOperator = /[*/+-]$/;
const digitsOperatordigits = /^\d+[*/+-]\d+$/;
const onlyOperator = /^[*/+-]$/;
export default function (state = '0', action) {
switch (action.type) {
case EQUALS_CLICK:
if (/\d[*/+-]\d/.test(state)) { return parseFloat(eval(state).toFixed(4)); }
return state;
case OPERATOR_CLICK:
if (state.length > 15) { return state; }
else if (onlyOperator.test(state) && /[/*]/.test(action.payload)) {
return state;
} else if (endsWithOperator.test(state)) {
return `${state.slice(0, -1)}${action.payload}`;
} else if (digitsOperatordigits.test(state)) {
return `${state}${action.payload}`;
} else if (state === '0') {
if (/[-+]/.test(action.payload)) { return action.payload; }
return state;
}
return `${state}${action.payload}`;
I’m handling the equals case first, It returns the result and then state is – the result. Any further calculations are done on the result unless AC is clicked. It’s working but not passing tests.
Please help!