Tell us what’s happening:
Describe your issue in detail here.
My code works when I manually test it. But it shows completely absurd results when tested automatically by freecodecamp. I do not know if it’s a browser issue or if I actually do have an error in my code. But when for example manually testing one of their automatic test cases which is “5*-+5” I get 10, which is the correct result, but on their that equals to 255. I am losing my mind.
Your code so far
import { createRoot } from "https://esm.sh/react-dom@18.2.0/client";
import * as mathjs from "https://cdn.skypack.dev/mathjs@11.5.0";
const buttons = [
{ id: "clear", child: "AC" },
{ id: "divide", child: "/" },
{ id: "multiply", child: "*" },
{ id: "seven", child: "7" },
{ id: "eight", child: "8" },
{ id: "nine", child: "9" },
{ id: "subtract", child: "-" },
{ id: "four", child: "4" },
{ id: "five", child: "5" },
{ id: "six", child: "6" },
{ id: "add", child: "+" },
{ id: "one", child: "1" },
{ id: "two", child: "2" },
{ id: "three", child: "3" },
{ id: "equals", child: "=" },
{ id: "zero", child: "0" },
{ id: "decimal", child: "." }
];
const App = () => {
const [value, setValue] = useState("0");
return (
<main>
<div id="display">{value}</div>
{buttons.map((e) => (
<Button myId={e.id} myChild={e.child} value={value} setValue={setValue} />
))}
</main>
);
};
const Button = ({myId, myChild, value, setValue}) => {
const handleClick = (event) => {
switch (myChild) {
case "AC":
setValue("0");
break;
case "=":
const matchedNumbers = String(value).match(/([^\D]+)/g);
const matchedSymbols = String(value).match(/([^0-9]+)/g);
let result = "";
for (let i = 0; i < matchedSymbols.length; i++) {
const lastCharacter = matchedSymbols[i].charAt(matchedSymbols[i].length - 1);
console.log("last character : " + lastCharacter);
if (lastCharacter === "-" && matchedSymbols[i].length >= 2) {
matchedSymbols[i] = matchedSymbols[i].slice(-2);
}
else if (lastCharacter !== "-") {
matchedSymbols[i] = matchedSymbols[i].slice(-1);
}
result += matchedNumbers[i] + matchedSymbols[i]
}
if (matchedNumbers.length + 1 > matchedSymbols.length) {
result += matchedNumbers[matchedNumbers.length - 1];
}
console.log("result : " + result);
console.log("evaluated result : " + String(mathjs.evaluate(result)));
setValue(String(mathjs.evaluate(result)));
break;
case ".":
const valueTemp = value;
const splitValueNumbers = valueTemp.split(/[-+/*]/);
const lastNumber = splitValueNumbers[splitValueNumbers.length - 1];
if (!lastNumber.includes(".")) {
setValue(value + myChild);
}
break;
default:
if (value === "0") {
setValue(myChild);
return;
}
setValue(value + myChild);
break;
}
}
return <button id={myId} onClick={handleClick}>{myChild}</button>
}
createRoot(document.getElementById("root")).render(<App />);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:108.0) Gecko/20100101 Firefox/108.0
Challenge: Front End Development Libraries Projects - Build a JavaScript Calculator
Link to the challenge: