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. 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

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

              
                #wrapper
  #app
              
            
!

CSS

              
                html,body 
  width: 100vw
  height: 100vh
  padding: 0
  margin: 0

body
  background: linear-gradient(-15deg, hsl(210,30%,37%), hsl(40,20%,70%))
  color: #fff
  font-family: 'Oswald', Arial, Helvetica, sans-serif
  font-weight: 400
 
#wrapper
  
  h1
    font-family: 'Pacifico', Arial, Helvetica, sans-serif
    text-shadow: 1px 1px 3px rgba(0,0,0,0.5)
    font-size: 32px
    font-weight: 100
    

  .calculator
    text-align: center
    
    
      
    .calculator-box
      max-width: 400px
      background: rgba(0,0,0,0.35)
      margin: 0 auto
      padding: 13px
      border: 3px solid rgba(255,255,255,.4)
      box-shadow: 0px 0px 75px 10px rgba(0,0,0,0.4)
      
      h1
        font-family: 'Oswald', Arial, Helvetica, sans-serif
        font-size: 28px
        font-weight: 700
        
    .buttonContainer
      display: grid 
      grid-template-columns: auto auto auto auto
      grid-gap: 0px
      text-align: center 
    
      & > div
        & > span
          display: flex
          background: rgba(0,0,0,0.3)
          color: #fff
          padding: 1em
          margin: 2px
          min-height: calc(100% - 4px)
          text-align: center
          align-items: center
          justify-content: center
          box-sizing: border-box
          cursor: pointer
          &:hover
            background: rgba(0,0,0,0.45)
            
          &:active
            background: rgba(0,0,0,0.55)
            box-shadow: inset 3px 3px 8px rgba(0,0,0,0.7)
            color: #fff
            font-weight: bold
      & #clear
        grid-area: 1 / 1 / span 1 / span 2 
        & span
          background: rgba(255,0,0,0.5)
        
      & #subtract
          grid-area: 2 / 4
          
      & #add
          grid-area: 3 / 4
          
      & #equals
          grid-area: 4 / 4 / 2 span / 1 span
          & span
            background: rgba(0,0,0,0.5)
      & #zero
          grid-area: 5 / 1 / 1 span / 2 span
  
      
              
            
!

JS

              
                const buttonType = {
    Number: "Number",
    Formula: "Formula"
}

const buttons = [
    { label: "AC", type: buttonType.Formula, id: "clear" },
    { label: "/", type: buttonType.Formula, id: "divide" },
    { label: "*", type: buttonType.Formula, id: "multiply" },
    { label: "-", type: buttonType.Formula, id: "subtract" },
    { label: "+", type: buttonType.Formula, id: "add" },
    { label: "=", type: buttonType.Formula, id: "equals" },

    { label: "7", type: buttonType.Number, id: "seven" },
    { label: "8", type: buttonType.Number, id: "eight" },
    { label: "9", type: buttonType.Number, id: "nine" },

    { label: "4", type: buttonType.Number, id: "four" },
    { label: "5", type: buttonType.Number, id: "five" },
    { label: "6", type: buttonType.Number, id: "six" },

    { label: "1", type: buttonType.Number, id: "one" },
    { label: "2", type: buttonType.Number, id: "two" },
    { label: "3", type: buttonType.Number, id: "three" },

    { label: "0", type: buttonType.Number, id: "zero" },
    { label: ".", type: buttonType.Number, id: "decimal" },

];

const style = {
    displayWrapper: {
        background: "hsl(167,5%,51%)",
        boxShadow: "inset 5px 5px 5px rgba(0,0,0,0.5)",
        padding: "5px 15px",
        margin: "16px 3px",
        border: "1px solid rgba(0,0,0,0.3)",
    },
    display: {
        textAlign: "right",
        margin: 0,
        textShadow: "1px 1px 2px rgb(0,0,0)",
    },
    history: {
        display: "flex",
        justifyContent: "flex-end",
        margin: 0,
        color: "black",
    },
    historyItem: {
        background: "rgba(255,255,255,0.5)",
        padding: "2px 6px",
        margin: 5,
        borderRadius: 15,
        boxShadow: "2px 2px 2px rgba(0,0,0,0.5)",
    }
}
const INITIAL_VALUE = {
    display: "0",
    history:[]
}
const MAXLIMIT = "MAX LIMIT";
const OPARETORS = /[^0-9.=]+/; 
const KEYS = /[0-9*.\/+=-]/
class Calculator extends React.Component {
    
    constructor(props) {
        super(props);
        this.state = JSON.parse(JSON.stringify(INITIAL_VALUE));
    }

    componentWillMount(){
        window.onkeyup = (e)=>{
            if (KEYS.test(e.key))
                this.buttonClicked({ label: e.key })
            else if (e.keyCode == 27)
                this.buttonClicked({ label:"AC" })
            else if (e.keyCode == 13)
                this.buttonClicked({label:"="})
        }
    }

    buttonClicked = btnProps => {
        let currentValue = btnProps.label;
        
        //clear value if cancel
        if (currentValue === 'AC') {
            this.setState(JSON.parse(JSON.stringify(INITIAL_VALUE)));
            return;
        }
        //check max limit
        if(this.state.display.length>10 || this.state.display === MAXLIMIT){
            this.setState({
                display:MAXLIMIT
            })
            return;
        }
        if (currentValue === '=') {
            let display  = this.evaluate(this.state.display);
            let history = this.addToHistory(this.state.history, this.state.display, display);
            this.setState({display, history});
            return;
        }
        //ignore second DOT (.)
        if(currentValue === '.'){
            let mix = this.state.display + currentValue;
            if(mix.match(/[.]+[0-9]+[.]/) || mix.match(/[.]+[.]/))
                return;
        }
        this.setState(ps=>{
            //check if last charactor is operator 
            //chekc if current charactor is operator
            //if both operator then check is one or more
            //if more than evaluate and result should be new outup which is going to set as display
            
            let output = ps.display;
            let isLastOperator = OPARETORS.test(output.charAt(output.length-1));
            let isAgainOperator = !isLastOperator && OPARETORS.test(output) && OPARETORS.test(currentValue)? true:false;
            
            //if operatoris repleated then evaluate the value retrun it
            if(isAgainOperator){
                let display = this.evaluate(output);
                let history = this.addToHistory(ps.history, output, display);
                ps.display = display;
                ps.history = history;
                if(display === "0")
                    return ps;
            }
            //replace last charactor
            if(isLastOperator && OPARETORS.test(currentValue)){
                if(currentValue==="-"){
                    ps.display = output.replace(/[*+\/-]+[-]/,"-") + currentValue
                }else if(output.match(/[*+\/-]+[-]/)){
                    ps.display = output.replace(/[*+\/-]+[-]/, currentValue);
                }else{
                    ps.display =  output.replace(/.$/, currentValue);
                }
            }else{
                ps.display = output === "0"? currentValue : ps.display + currentValue;
            }
            
            return ps;
        })
    }

    evaluate = (output) => {
        try{
            return eval(output.split("--").join("+")).toString();
        }catch(e){
            return  "0";
        }
    }
    addToHistory = (his, oparation, result)=>{
        let history = [...his, {oparation, result}];
        if(history.length>4){
            history.shift();
        } 
        return history;
    }
    render() { 
        return (
            <div className="calculator">
                <h1>Calculator</h1>
                <div className="calculator-box">
                    <Display display={this.state.display} history={this.state.history}/>
                    <Buttons click={this.buttonClicked} />
                </div>
                <p>Support keyboard and save history upto 4 records.</p>
            </div>
        )
    }
}

class Display extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        let history;
        if (this.props.history.length > 0) {
            history = this.props.history.map((his, index) => <span key={index} style={style.historyItem}>{his.oparation} = <b>{his.result}</b></span>);
        }
        return (
            <div style={style.displayWrapper}>
                <div style={style.history}>
                    {history}
                </div>
                <h1 id="display" style={style.display}>{this.props.display}</h1>
            </div>
        )
    }
}

class Buttons extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div className="buttonContainer">
                {
                    buttons.map(btn =>
                        <div key={btn.id} id={btn.id} onClick={() => { this.props.click(btn) }} className={"btn-" + btn.class}>
                            <span>{btn.label}</span>
                        </div>
                    )
                }
            </div>
        );
    };
};


ReactDOM.render(<Calculator />, document.getElementById("app")); 
              
            
!
999px

Console