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

              
                <body>
  <div id="root"></div>
</body>
              
            
!

CSS

              
                $calc-radius: 15px;

body {
  background-color: #dfa;
}

#calculator {
  background-color: #111;
  border-radius: $calc-radius;
}

#screen {
  background-color: #334;
  border-radius: $calc-radius;
  text-align: right;
  padding: 8px 10px;
  #statement {
    height: 25px;
  }
}

#body {
  padding: 8px;
}

.btn {
  width: 50px;
  height: 50px;
  border-radius: 25px;
  margin: 4px;
}

.btn-dark {
  background-color: #212529;
}

.btn-primary {
  background-color: #1e7fec;
  border-color: #1e7fec;
}

.btn-danger {
  background-color: #cb3545;
  border-color: #cb3545;
}

#backspace {
  background-color: #212529;
  border-color: #212529;
  color: white;
}

#equals {
  background-color: #aaddff;
  border-color: #aaddff;
}

.btn:hover {
  transform: scale(110%);
  box-shadow: 0px 0px 10px 0px #fff;
}

.btn-warning:hover {
  border-color: #ffc107 !important;
  box-shadow: 0px 0px 10px 0px #ffc107 !important;
}
              
            
!

JS

              
                // Paul Sedra
// 01-04-2022
// Purpose: A simple calculator

//! issues:
  // 1. parenthesis & sqrt do not work
  // 2. when there are lots of numbers in statement the calculator gets wonky

//@ extensions:
  // 1. add advaced calculator functions
  // 2. add history functionality
  // 3. change fonts, sizes

const initialState = {
  statement: [],
  result: "0"
}

const NUMBER = "NUMBER";
const DECIMAL = "DECIMAL";
const OPERAND = "OPERAND"
const DELETE = "DELETE";
const CLEAR = "CLEAR";
const CALC = "CALC";

const inputAction = (type, input) => ({ type: type, value: input });
const deleteAction = () => ({ type: DELETE });
const clearAction = () => ({ type: CLEAR });
const calcAction = (result) => ({ type: CALC, result: result });

const reducer = (state=initialState, action) => {
  switch (action.type) {
    case NUMBER:
      if (state.statement.length > 0) {
        if ( state.statement.at(-1) == "0" ) {
          return { statement: [...state.statement.slice(0, -1), action.value], result: action.value };
        } 
        if ( state.statement.at(-1).match(/[0-9]/) || state.statement.at(-2).match(/[x/+-]/) ) {
          return { statement: [...state.statement.slice(0, -1), state.statement.at(-1) + action.value],
                   result: state.statement.at(-1) + action.value };
        }
      }
      return { statement: [...state.statement, action.value], result: action.value };
    case DECIMAL:
      if ( state.statement.at(-1).match(/[x/+-]/) ) {
        return { statement: [...state.statement, "0"+action.value], result: "0"+action.value };
      }
      if ( !state.statement.at(-1).includes(".") ) {
        return { statement: [...state.statement.slice(0, -1), state.statement.at(-1) + action.value],
                 result: state.statement.at(-1) + action.value };
      }
      return state;
    case OPERAND:
      if ( state.statement.at(-1).match(/[x/+-]/) ) {
        if ( action.value == "-" && !state.statement.at(-2).match(/[x/+-]/) ) {
          return { statement: [...state.statement, action.value], result: action.value};
        } else if ( action.value != "-" && state.statement.at(-2).match(/[x/+-]/) ) {
          return { statement: [...state.statement.slice(0, -2), action.value], result: action.value };
        }
        return { statement: [...state.statement.slice(0, -1), action.value], result: action.value };
      }
      return { statement: [...state.statement, action.value], result: action.value };
    case DELETE:
      if ( state.statement.length > 1 ) {
        let newStatement = [...state.statement];
        newStatement.pop();
        return { statement: newStatement, result: "0" };
      }
      return initialState;
    case CLEAR:
      return initialState;
    case CALC:
      return { statement: [action.result.toString()] , result: action.result };
    default:
      return state;
  }
}

const store = Redux.createStore(reducer);

class Display extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div id="screen" class="w-100">
        <div id="statement" class="text-white">{this.props.statement.join(" ")}</div>
        <div id="display" class="text-white">{this.props.result}</div>
      </div>
    );
  }
}

class Body extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.handleDelete = this.handleDelete.bind(this);
    this.handleClear = this.handleClear.bind(this);
    this.handleCalculate = this.handleCalculate.bind(this);
  }
  handleClick(event) {
    this.props.newInput(event.target.name, event.target.innerHTML);
  }
  handleDelete(event) {
    this.props.delete();
  }
  handleClear(event) {
    this.props.clear();
  }
  handleCalculate() {
    var result = evaluateRPN(parseRPN(this.props.statement));
    this.props.calculate(result);
  }
  render() {
    return (
      <div id="body">
        <div id="row1">
          <button id="clear" class="btn btn-danger" onClick={this.handleClear}>AC</button>
          <button id="parenthesis" class="btn btn-primary">( )</button>
          <button id="sqrt" class="btn btn-primary">√</button>
          <button id="divide" class="btn btn-primary" name={OPERAND} onClick={this.handleClick}>/</button>
        </div>
        <div id="row2">
          <button id="seven" class="btn btn-dark" name={NUMBER} onClick={this.handleClick}>7</button>
          <button id="eight" class="btn btn-dark" name={NUMBER} onClick={this.handleClick}>8</button>
          <button id="nine" class="btn btn-dark" name={NUMBER} onClick={this.handleClick}>9</button>
          <button id="multiply" class="btn btn-primary" name={OPERAND} onClick={this.handleClick}>x</button>
        </div>
        <div id="row3">
          <button id="four" class="btn btn-dark" name={NUMBER} onClick={this.handleClick}>4</button>
          <button id="five" class="btn btn-dark" name={NUMBER} onClick={this.handleClick}>5</button>
          <button id="six" class="btn btn-dark" name={NUMBER} onClick={this.handleClick}>6</button>
          <button id="subtract" class="btn btn-primary" name={OPERAND} onClick={this.handleClick}>-</button>
        </div>
        <div id="row4">
          <button id="one" class="btn btn-dark" name={NUMBER} onClick={this.handleClick}>1</button>
          <button id="two" class="btn btn-dark" name={NUMBER} onClick={this.handleClick}>2</button>
          <button id="three" class="btn btn-dark" name={NUMBER} onClick={this.handleClick}>3</button>
          <button id="add" class="btn btn-primary" name={OPERAND} onClick={this.handleClick}>+</button>
        </div>
        <div id="row5">
          <button id="zero" class="btn btn-dark" name={NUMBER} onClick={this.handleClick}>0</button>
          <button id="decimal" class="btn btn-dark" name={DECIMAL} onClick={this.handleClick}>.</button>
          <button id="backspace" class="btn btn-warning" onClick={this.handleDelete}><i class="fas fa-backspace"></i></button>
          <button id="equals" class="btn btn-info" onClick={this.handleCalculate}>=</button>
        </div>
      </div>
    );
  }
}

class Calculator extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div id="container" class="d-flex flex-column justify-content-md-center align-items-center vh-100">
        <div id="calculator">
          <Display statement={this.props.statement} result={this.props.result}/>
          <div>
            <Body newInput={this.props.newInput} delete={this.props.delete} clear={this.props.clear} calculate={this.props.calculate} statement={this.props.statement}/>
          </div>
        </div>
      </div>
    );
  }
}

const mapStateToProps = (state) => ({ statement: state.statement, result: state.result })

const mapDispatchToProps = (dispatch) => {
  return {
    newInput: (type, input) => dispatch( inputAction(type, input) ),
    delete: () => dispatch( deleteAction() ),
    clear: () => dispatch( clearAction() ),
    calculate: (result) => dispatch( calcAction(result) )
  }
}

const Provider = ReactRedux.Provider;
const Container = ReactRedux.connect(mapStateToProps, mapDispatchToProps)(Calculator);

class App extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
	  return (
      <Provider store={store} class="container h-100">
        <Container />
      </Provider>
	  );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


// Reverse Polish Notation Calculator
// unnecessary but I wanted to because I recently learned about it (leetcode #150)
function evaluateRPN(rpn) {
  const OPERANDS = Object.keys(EVALUATE);   // gets a list of operands from the EVALUATE Object keys
  var total = rpn.slice();    // creates a copy of the rpn paramter || this is will be returned
  
  var i,e;  // to be used in for loop
  for ( i=0, e = total[i]; i<total.length; i++, e = total[i] ) {
    if ( OPERANDS.indexOf(e) != -1 ) {
      total.splice(i-2, 3, EVALUATE[e](total[i-2],total[i-1]));   // replaces expression with result
      i=0;    // resets index
    }
  }
  return total[0];
}

function parseRPN(standard) {
  var arr = standard.slice();   // duplicates the standard parameter
  var rpn = [];   // declares return Array
  var i,e,j;  // to be used in for loops
  // transforms strings to integers
  for ( i = 0, e = arr[i]; i<arr.length; i++, e = arr[i] ) {
    if ( e.match(/[0-9]/) ) {
      arr[i] = parseFloat(e);
    }
  }
  // three for loops to translate PEMDAS into RPN left-right order
  for ( i=0, e = arr[i]; i<arr.length; i++, e = arr[i] ) {
    for ( j=0; j<2; j++ ) {
      if ( e == ["x", "/"][j] ) {
        _handleTransform();
      }
    }
  }
  // middle loop accounts for addition and subtration between products and quotients
  var missed = [];
  for ( i=0, e = arr[i]; i<arr.length; i++, e = arr[i] ) {
    if ( typeof e != "number" && typeof arr[i-1] != "number" && typeof arr[i+1] != "number" ) {
      missed.unshift(arr.splice(i, 1)[0]);  
    }
  }
  rpn.push(...missed);
  for ( i=0, e = arr[i]; i<arr.length; i++, e = arr[i] ) {
    for ( j=0; j<2; j++ ) {
      if ( e == ["+", "-"][j] ) {
        _handleTransform();
      }
    }
  }
  // private method reorders the list when an operand has been found
  function _handleTransform() {
    if ( typeof arr[i-1] == "number" ) {
      rpn.push(arr.splice(i-1, 1)[0]);  // value behind
      i--;
    }
    if ( typeof arr[i+1] == "number" ) {
      rpn.push(arr.splice(i+1, 1)[0]);  // value ahead
    }
    rpn.push(arr.splice(i, 1)[0]);  // operand
    i--;
  }
  return rpn;
}

// a simple way to evaluate an expression of two values when the operand is unknown
const EVALUATE = {
  "x": function(a,b){return a*b},
  "/": function(a,b){return a/b==Infinity? 0 : a/b},
  "+": function(a,b){return a+b},
  "-": function(a,b){return a-b},
};

              
            
!
999px

Console