I cannot figure out how to pass this challenge:
13. If 2 or more operators are entered consecutively, the operation performed should be the last operator entered (excluding the negative (-) sign.
The
Here is the method that is controlling the output. Note that the else if
statement !endsWithNegativeSign.test(formula)
is where near where this issue lies.
getOperator(e) {
const endsWithOperator = /[x+‑/]$/,
endsWithNegativeSign = /[x/+]‑$/;
if (!this.state.curValue.includes('Digit')) {
const value = e.target.value;
const { formula, preValue, evaluated } = this.state;
this.setState({ curValue: value, evaluated: false });
if (evaluated) {
this.setState({ formula: preValue + value });
} else if (!endsWithOperator.test(formula)) {
this.setState({
prevVal: formula,
formula: formula + value
});
} else if (!endsWithNegativeSign.test(formula)) {
this.setState({
formula: value + (endsWithNegativeSign.test(formula + value)
? formula : preValue) + value // This is the line controlling output.
});
} else if (value !== '‑') {
this.setState({
formula: preValue + value
});
}
}
}
This is the evaluate method as well, which could also be part of the problem.
evaluate() {
if (!this.state.curValue.includes(`Digit`) && !this.state.evaluated && !endsWithNegativeSign.test(this.state.formula)) {
let exp = this.state.formula;
while (endsWithOperator.test(exp)) {
exp = exp.slice(0, -1);
}
exp = exp.replace(/x/g, `*`).replace(/-/g, '-');
let ans = eval(exp);
if (ans){
this.setState({
curValue: ans.toString(),
formula: exp.replace(/\*/g, '⋅').replace(/-/g, '‑') + '=' + ans,
preValue: ans,
evaluated: true
})};
}
}
Here is a link to the Demo.
And here is the Repository.
Any help would be appreciated on this. Thanks in advance!