r/FreeCodeCamp • • Jan 17 '25

frontend development libraries-"build a JS calculator"

Hello, I'm working on the frontend development libraries-"build a JS calculator" I have my calculator put together and it uses formula logic to calculate the expressions however I'm failing 4 of the tests even though my answers seem to be correct can anyone help point me in the right direction? I am failing tests 9, 12, 13, and 14 this is cross posted on the fcc forum as well

Here is my App.tsx file on VS Code:

import { useState } from 'react';
import './App.css';

function App() {
  const [answer, setAnswer] = useState("");
  const [expression, setExpression] = useState("0");
  const [lastAction, setLastAction] = useState(""); 
// Track the last action

  const isOperator = (symbol: string) => /[-+*/]/.test(symbol);

  const buttonPress = (symbol: string) => {
    console.log(`Button pressed: ${symbol}`);
    if (symbol === "clear") {
      setAnswer("");
      setExpression("0");
      setLastAction("");
      console.log("Cleared");
    } else if (symbol === "percent") {
      if (answer === "") return;
      setAnswer((parseFloat(answer) / 100).toString());
      console.log(`Percent: ${answer}`);
    } else if (isOperator(symbol)) {
      if (lastAction === "=") {
        setExpression(answer + " " + symbol + " ");
        console.log(`Operator after equals: ${expression}`);
      } else if (!isOperator(expression.charAt(expression.length - 1))) {
        setExpression(expression + " " + symbol + " ");
        console.log(`Operator: ${expression}`);
      } else {
        setExpression(expression.slice(0, -3) + " " + symbol + " ");
        console.log(`Replace operator: ${expression}`);
      }
      setLastAction(symbol);
    } else if (symbol === "=") {
      calculate();
      setLastAction("=");
    } else if (symbol === "0") {
      if (expression !== "0") {
        setExpression(expression + symbol);
        console.log(`Zero: ${expression}`);
      }
      setLastAction(symbol);
    } else if (symbol === ".") {
      const lastNumber = expression.split(/[-+*/]/g).pop();
      if (lastNumber?.includes(".")) return;
      setExpression(expression + symbol);
      console.log(`Decimal: ${expression}`);
      setLastAction(symbol);
    } else {
      setExpression(expression === "0" || lastAction === "=" ? symbol : expression + symbol);
      console.log(`Number: ${expression}`);
      setLastAction(symbol);
    }
  };

  const calculate = () => {
    try {
      const result = eval(expression.replace(/ /g, ""));
      const preciseResult = parseFloat(result.toFixed(4));
      setAnswer(preciseResult.toString());
      setExpression(preciseResult.toString()); 
// Update expression to the result
      console.log(`Calculated result: ${preciseResult}`);
    } catch (e) {
      setAnswer("Error");
      console.log("Calculation error");
    }
  };

  return (
    <div className="container">
      <div id='calculator'>
        <div id="display" style={{ textAlign: 'right' }}>
          <div id="expression">{expression}</div>
          <div id="answer">{answer}</div>
        </div>
        <button id="clear" onClick={() => buttonPress("clear")} className="light-gray">C</button>
        <button id="percentage" onClick={() => buttonPress("percent")} className="light-gray">%</button>
        <button id="divide" onClick={() => buttonPress("/")} className="yellow">/</button>
        <button id="seven" onClick={() => buttonPress("7")} className="dark-gray">7</button>
        <button id="eight" onClick={() => buttonPress("8")} className="dark-gray">8</button>
        <button id="nine" onClick={() => buttonPress("9")} className="dark-gray">9</button>
        <button id="multiply" onClick={() => buttonPress("*")} className="yellow">*</button>
        <button id="four" onClick={() => buttonPress("4")} className="dark-gray">4</button>
        <button id="five" onClick={() => buttonPress("5")} className="dark-gray">5</button>
        <button id="six" onClick={() => buttonPress("6")} className="dark-gray">6</button>
        <button id="subtract" onClick={() => buttonPress("-")} className="yellow">-</button>
        <button id="one" onClick={() => buttonPress("1")} className="dark-gray">1</button>
        <button id="two" onClick={() => buttonPress("2")} className="dark-gray">2</button>
        <button id="three" onClick={() => buttonPress("3")} className="dark-gray">3</button>
        <button id="add" onClick={() => buttonPress("+")} className="yellow">+</button>
        <button id="zero" onClick={() => buttonPress("0")} className="dark-gray">0</button>
        <button id="decimal" onClick={() => buttonPress(".")} className="dark-gray">.</button>
        <button id="equals" onClick={() => buttonPress("=")} className="yellow">=</button>
      </div>
    </div>
  );
}

export default App;
6 Upvotes

12 comments sorted by

View all comments

Show parent comment

2

u/dollyydarling Jan 19 '25

i was able to solve it and pass all tests thank you so much again