I am working on the freeCodeCamp JavaScript calculator project and after getting most of the other functionalities properly implemented I’m stuck on test number 13 which basically says that a sequence like “5 * - + 5” = should produce an output of “10” i.e., if 2 or more operators are entered consecutively, the operation performed should be the last operator entered (excluding the negative (-) sign).
I tried different versions of the chooseOperation method Initially this
chooseOperation = (op) => {
const { previous, current, operation } = this.state;
if (previous !== "" && current !== "") {
this.compute();
}
this.setState(
(prevState) => ({
operation: op,
previous:
prevState.current === "" ? prevState.previous : prevState.current,
current: "",
})
);
};
then this
chooseOperation = (op) => {
const { previous, current, operation } = this.state;
if (previous !== "" && current !== "") {
this.compute();
}
if (operation !== "" && op === "-" && previous !== "" && current === "") {
this.setState((prevState) => ({
current: `-${prevState.current}`,
previous: prevState.previous,
operation: prevState.operation,
}));
} else {
this.setState(
(prevState) => ({
operation: op,
previous:
prevState.current === "" ? prevState.previous : prevState.current,
current: "",
}),
() => {
console.log(this.state.operation);
console.log(previous);
console.log(current);
}
);
}
};
and then this
chooseOperation = (op) => {
const { previous, current, operation } = this.state;
if (previous !== "" && current !== "") {
this.compute();
}
if (operation !== "" && op === "-" && previous !== "" && current === "") {
this.setState((prevState) => ({
current: `-${prevState.current}`,
previous: prevState.previous,
operation: prevState.operation,
}));
} else if (
operation !== "" &&
op !== "-" &&
previous !== "" &&
current === "-"
) {
this.setState((prevState) => ({
current: `${prevState.current}`,
previous: `${prevState.previous}`,
operation: op,
}));
} else {
this.setState(
(prevState) => ({
operation: op,
previous:
prevState.current === "" ? prevState.previous : prevState.current,
current: "",
})
);
}
};
none of them worked though,
the codepen link to the project : https://codepen.io/donjoe21915/pen/jOJOzXJ