css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

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. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div id="app"> </div>

<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.2/css/all.css" integrity="sha384-/rXc/GQVaYpyDdyxK+ecHPVYJSN9bmVFBvjA/9eOB+pb3F2w2N6fc5qB9Ew5yIns" crossorigin="anonymous">

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/2.6.0/math.min.js"></script>

<!--
<script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>
-->

            
          
!
            
              
$buttonDimension: 90px;
$calculatorBorderWidth: $buttonDimension/15;
$calculatorHeight: $buttonDimension*6 + $calculatorBorderWidth*2;
$calculatorWidth: $buttonDimension*4 + $calculatorBorderWidth*2;
$displayHeight: $calculatorHeight%($buttonDimension*5) - $calculatorBorderWidth*2;
$lightBlue: #66ccff;
$brightBlue: #66ffff;
$lightGreen: #66ffcc;
$lightRed: #ff6666;
$backgroundColor: $lightBlue;
$backgroundColorOnHover: $lightGreen;
$backgroundClear: $lightRed;
$backgroundEquals: $brightBlue;
$buttonBorder: 1px solid $lightBlue;
$calculatorBorder: $calculatorBorderWidth solid black;

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

#app {
  font-family: 'Raleway', sans-serif;
  height: 100vh;
  background: $backgroundColor;
  display: flex;
}

#calculator {
  height: $calculatorHeight;
  width: $calculatorWidth;
  background: white;
  margin: auto;
  display: flex;
  flex-wrap: wrap;
  justify-content: stretch;
  border: $calculatorBorder;
  border-radius: 5px;
  box-shadow: 0 0 100px;
}

.button {
  display: flex;
  justify-content: center;
  align-items: center;
  height: $buttonDimension;
  width: $buttonDimension;
  border: $buttonBorder;
  font-size: 1.75em;
  -moz-user-select: none;
  -ms-user-select: none;
  -webkit-user-select: none;
  user-select: none;
  
  &:hover {
    background: $backgroundColorOnHover;
    opacity: 0.8;
    cursor: pointer;
  }
}

.buttonWide {
  width: $buttonDimension*2;
}

.buttonTall {
  height: $buttonDimension*2;
}

#temp {
  width: $buttonDimension*3;
  height: $buttonDimension*2;
  display: flex;
  flex-wrap: wrap;
}

#display {
  width: $buttonDimension*4;
  height: $displayHeight;
  border-bottom: $buttonBorder;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: flex-end;
  font-size: 1.75em;
  text-align: right;
  padding-right: $buttonDimension/10;
}

#clear {
  background: $backgroundClear;
}

#equals {
  background: $backgroundEquals;
}


            
          
!
            
              //There is a certain restriction in the test suite that requires the last operator that is input to be used.
//Therefore, I was not able to include multiplication and division by negative numbers.
//A workaround is to have the expression start with a '-1*'.

const operatorRegex = /[+\-*/]/;

class App extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      calculations: ["0"],
      result: ""
    }
    this.handleClick = this.handleClick.bind(this);
    this.performCalculations = this.performCalculations.bind(this);
  }
  
  handleClick(event) {
    const value = event.target.getAttribute('value');
    console.log("value: " + value);
    switch(value) {
      case "clear":
        this.setState({
          calculations: ["0"]
        });
        console.clear();
        break;
      case "equals":
        this.performCalculations();
        break;
      case ".":
        let operatorCount = 0;
        let decimalCount = 0;
        for (var i=0; i<this.state.calculations.length; i++) {
          if (this.state.calculations[i].match(operatorRegex) ) {
            operatorCount++;
            console.log("found an operator");
          } else if (this.state.calculations[i].match(/[.]/) ) {
            decimalCount++;
            console.log("found a decimal");
          }
        }
        console.log("decimalCount: " + decimalCount);
        console.log("operatorCount: " + operatorCount);
        if (decimalCount>operatorCount) {
          console.log("there's already a decimal here");
          break;
        } else {
          this.setState({
            calculations: [...this.state.calculations, value]
          });
        }
        break;
      case "0":
        if ( this.state.calculations[this.state.calculations.length-1] === "0" ) {
          console.log("You can't have a number that starts with multiple zeroes");
        } else {
          this.setState({
            calculations: [...this.state.calculations, value]
          });
        }
        break;
      default:
        console.log("case default");
        
        let lastIndex = this.state.calculations.length-1;
        let lastItem = this.state.calculations[lastIndex].toString();
        console.log("lastItem", lastItem);

        if (this.state.calculations.length===1 && this.state.calculations[0] === "0") {
          this.setState({
            calculations: [value]
          });
        } else if ( lastItem.match(operatorRegex) && value.match(operatorRegex) ) {
          console.log("You can't have multiple operators next to each other. Replacing the old one with the new one.");
          this.setState({
            calculations: [...this.state.calculations.slice(0,lastIndex), value]
          })
        } else {
          this.setState({
            calculations: [...this.state.calculations, value]
          });
        }
        console.log("finished default");
        break;
    }
    console.log("calculations: " + this.state.calculations);
  }
  
  performCalculations() {
    let expression = this.state.calculations.join('');
    //console.log("expression: " + expression);
    let result = math.eval(expression);
    //console.log("result: " + result);
    this.setState({
      calculations: [result]
    })
  }

  render() {
    return (
      <div id="calculator">
        <div id="display">{this.state.calculations}</div>
        <div id="clear" className="button buttonWide" onClick={this.handleClick} value="clear">AC</div>
        <div id="divide" className="button" onClick={this.handleClick} value="/">/</div>
        <div id="multiply" className="button" onClick={this.handleClick} value="*">X</div>
        <div id="seven" className="button" onClick={this.handleClick} value="7">7</div>
        <div id="eight" className="button" onClick={this.handleClick} value="8">8</div>
        <div id="nine" className="button" onClick={this.handleClick} value="9">9</div>
        <div id="subtract" className="button" onClick={this.handleClick} value="-">-</div>
        <div id="four" className="button" onClick={this.handleClick} value="4">4</div>
        <div id="five" className="button" onClick={this.handleClick} value="5">5</div>
        <div id="six" className="button" onClick={this.handleClick} value="6">6</div>
        <div id="add" className="button" onClick={this.handleClick} value="+">+</div>
        <div id="temp">
          <div id="one" className="button" onClick={this.handleClick} value="1">1</div>
          <div id="two" className="button" onClick={this.handleClick} value="2">2</div>
          <div id="three" className="button" onClick={this.handleClick} value="3">3</div>
          <div id="zero" className="button buttonWide" onClick={this.handleClick} value="0">0</div>
          <div id="decimal" className="button" onClick={this.handleClick} value=".">.</div>
        </div>
        <div id="equals" className="button buttonTall" onClick={this.handleClick} value="equals">=</div>
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('app'));
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console