Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>
<link
      href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700;900&display=swap"
      rel="stylesheet"
    />

<!-- 

Hello Camper!

For now, the test suite only works in Chrome! Please read the README below in the JS Editor before beginning. Feel free to delete this message once you have read it. Good luck and Happy Coding! 

- The freeCodeCamp Team 

-->

<div id="App"></div>
              
            
!

CSS

              
                // VARIABLES

$FONT: "Roboto", sans-serif;
$OPERATOR: #11d7fa;
$BLACK: #1f1f1f;
$MIDGREY: #c1c1c2;
$LIGHTGREY: #d6d5da;

// RESETS
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  text-align: center;
  transition: all 100ms ease;
}

html {
  background: white;
  font-size: 10px;
  font-family: $FONT;
}

h1 {
  margin-top: 5rem;
  font-size: 5rem;
}

#calculator {
  margin: 0 auto;
  margin-top: 3rem;
  width: 325px;
  font-size: 2rem;
  border: 1px solid $BLACK;
  border-radius: 1rem;
  padding: 0.5rem;
  background: $BLACK;
  box-shadow: 0px 0px 30px rgb(160, 158, 158);

  .btn-section {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-auto-rows: minmax(7.5rem, 1fr);
    grid-gap: 0.3rem;
  }

  button {
    border: 0.1px solid $BLACK;
    border-radius: 2px;
    font-size: 2.5rem;
    outline: none;

    &:active {
      transform: scale(0.95);
    }
  }

  .operator {
    background: $OPERATOR;
    font-weight: bold;
    font-size: 2.1rem;
    cursor: pointer;

    &:hover {
      background: darken($OPERATOR, 10%);
    }
  }

  .number {
    background: $LIGHTGREY;
    font-weight: bold;
    cursor: pointer;

    &:hover {
      background: darken($LIGHTGREY, 10%);
    }
  }


  #equation, #display {
    text-align: right;
    background: lighten($BLACK, 20%);
    padding: 0.5rem;
  }

  #equation {
    min-height: 3rem;
    font-size: 1.5rem;
    color: $LIGHTGREY;
  }

  #display {
    font-size: 4rem;
    margin-top: 0.5rem;
    margin-bottom: 0.5rem;
    color: white;
  }
  

  #clear {
    grid-column: span 2;
    background: $MIDGREY;
    cursor: pointer;

    &:hover {
      background: darken($MIDGREY, 10%);
    }
  }

  #zero {
    grid-column: span 2;
  }
}

              
            
!

JS

              
                // !! IMPORTANT README:

// You may add additional external JS and CSS as needed to complete the project, however the current external resource MUST remain in place for the tests to work. BABEL must also be left in place. 

/***********
INSTRUCTIONS:
  - Select the project you would 
    like to complete from the dropdown 
    menu.
  - Click the "RUN TESTS" button to
    run the tests against the blank 
    pen.
  - Click the "TESTS" button to see 
    the individual test cases. 
    (should all be failing at first)
  - Start coding! As you fulfill each
    test case, you will see them go   
    from red to green.
  - As you start to build out your 
    project, when tests are failing, 
    you should get helpful errors 
    along the way!
    ************/

// PLEASE NOTE: Adding global style rules using the * selector, or by adding rules to body {..} or html {..}, or to all elements within body or html, i.e. h1 {..}, has the potential to pollute the test suite's CSS. Try adding: * { color: red }, for a quick example!

// Once you have read the above messages, you can delete all comments. 

function App() {
  // DATA
  const buttons = [
    {
      value: "init",
      content: "C",
      id: "clear",
      className: "number",
    },
    {
      value: "%",
      content: <i className="fas fa-percent"></i>,
      id: "percent",
      className: "operator",
    },
    {
      value: "/",
      content: <i className="fas fa-divide"></i>,
      id: "divide",
      className: "operator",
    },
    {
      value: "7",
      content: "7",
      id: "seven",
      className: "number",
    },
    {
      value: "8",
      content: "8",
      id: "eight",
      className: "number",
    },
    {
      value: "9",
      content: "9",
      id: "nine",
      className: "number",
    },
    {
      value: "*",
      content: <i className="fas fa-times"></i>,
      id: "multiply",
      className: "operator",
    },
    {
      value: "4",
      content: "4",
      id: "four",
      className: "number",
    },
    {
      value: "5",
      content: "5",
      id: "five",
      className: "number",
    },
    {
      value: "6",
      content: "6",
      id: "six",
      className: "number",
    },
    {
      value: "-",
      content: "-",
      id: "subtract",
      className: "operator",
    },
    {
      value: "1",
      content: "1",
      id: "one",
      className: "number",
    },
    {
      value: "2",
      content: "2",
      id: "two",
      className: "number",
    },
    {
      value: "3",
      content: "3",
      id: "three",
      className: "number",
    },
    {
      value: "+",
      content: "+",
      id: "add",
      className: "operator",
    },
    {
      value: "0",
      content: "0",
      id: "zero",
      className: "number",
    },
    {
      value: ".",
      content: ".",
      id: "decimal",
      className: "number",
    },
    {
      value: "=",
      content: "=",
      id: "equals",
      className: "operator",
    },
  ];

  // STATE
  const [input, setInput] = React.useState("0");
  const [formula, setFormula] = React.useState("");
  const [equals, setEquals] = React.useState(false);
  const [result, setResult] = React.useState();
  const [value, setValue] = React.useState("0");

  // OPERATOR REGEXPs
  const operatorRegExp = /[*+/-]/;
  const endsWithOperator = /[*+-/]$/;

  // USE EFFECTS
  // evaluate formula when equals state changes
  React.useLayoutEffect(() => {
    if (equals) {
      let cleanedFormula = formula;
      while (endsWithOperator.test(cleanedFormula)) {
        cleanedFormula = cleanedFormula.slice(0, -1);
      }

      function solve(sum) {
        return eval(sum);
      }
      const answer =
        Math.round(1000000000 * solve(cleanedFormula)) / 1000000000;
      setResult(answer);
      setFormula(`${cleanedFormula} = ${answer}`);
      setInput(answer.toString());
    }
  }, [equals]);

  // run whenever value state changes
  React.useLayoutEffect(() => {
    handleButtons(value);
  }, [value]);

  // run whenever input state changes
  React.useLayoutEffect(() => {
    if (input.length > 11) {
      setInput("MAX LIMIT");
    }
  }, [input]);

  // KEYBOARD FUNCTIONALITY
  React.useLayoutEffect(() => {
    document.onkeydown = (e) => {
      const keyPress = e.key;
      switch (keyPress) {
        case "Enter":
          setValue("=");
          break;
        case "c":
          setValue("init");
          break;
        case " ":
          setValue("0");
          break;
        case "x":
          setValue("*");
          break;
        default:
          setValue(e.key);
          break;
      }
    };
  });

  // HANDLERS
  const handleClear = () => {
    setInput("0");
    setFormula("");
    setEquals(false);
  };

  const handleClick = (e) => {
    setValue(e.currentTarget.value);
  };

  const handleButtons = (value) => {
    if (input.length > 11) {
      setInput("MAX LIMIT");
      return;
    }
    if (input.includes("LIMIT") && value !== "init") {
      return;
    }
    if (!Number.isNaN(Number(value))) {
      // IF NUMBER
      if (equals) {
        handleClear();
        setInput(value);
        setValue("");
      } else if (input.match(operatorRegExp)) {
        setFormula(formula.concat(` ${input}`));
        setInput(value);
        if (value !== "0") {
          setValue("");
        }
      } else if (input === "0" && value === "0") {
        return;
      } else if (input === "0") {
        setInput(value);
        setValue("");
      } else {
        setInput(input.concat(value));
        setValue("");
      }
    } else if (value.match(operatorRegExp)) {
      // ELSE IF OPERATOR
      if (equals) {
        setFormula(result.toString());
        setInput(value);
        setEquals(false);
      } else {
        if (input === "0" && value === "-") {
          if (value === "-") {
            setInput(value);
          } else return;
        } else if (
          input.match(/[*+/]/) &&
          input.length === 1 &&
          value === "-"
        ) {
          setInput(input.concat(value));
        } else if (!input.match(operatorRegExp)) {
          setFormula(formula.concat(` ${input}`));
          setInput(value);
        } else {
          setInput(value);
        }
      }
    } else {
      switch (value) {
        case "init":
          handleClear();
          break;
        case ".":
          if (input.match(operatorRegExp)) {
            setFormula(formula.concat(` ${input}`));
            setInput("0.");
          } else if (!input.includes(".")) {
            setInput(input.concat(value));
          }
          break;
        case "=":
          if (!equals) {
            setFormula(formula.concat(` ${input}`));
            setEquals(true);
          }
          break;
        case "%":
          const x = parseFloat(input);
          const y = (Math.round(1000000 * (x / 100)) / 1000000).toString();
          setInput(y);
          break;
        default:
          return;
      }
      return;
    }
    return;
  };

  return (
    <>
      <h1>Calcleator</h1>
      <div id="calculator">
          <p id="equation">{formula}</p>
          <p id="display">{input}</p>
        <div className="btn-section">
          {buttons.map((btn, idx) => (
            <button
              onClick={handleClick}
              id={btn.id}
              className={btn.className}
              key={idx}
              value={btn.value}
            >
              {btn.content}
            </button>
          ))}
        </div>
      </div>
    </>
  );
}

ReactDOM.render(<App />, document.getElementById('App'));
              
            
!
999px

Console