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

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

CSS

              
                html {
  box-sizing: border-box;
}
*,*:after,*:before {
  box-sizing: inherit;
}

body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}

#root {
  height: 100vh;
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  grid-template-rows: 1fr auto 1fr;
  background: #052138;
  background: radial-gradient(#344f65 5%, #052138 55%, #111 98%);
}

.calculator {
  grid-row: 2;
  grid-column: 2;
  display: grid;
  grid-template-rows: auto 1fr;
  grid-gap: 1rem;
  border: 1px solid #fff;
  padding: 1rem;
  color: #fff;
  width: 17rem;
  background: #052138;
  font-size: 1.5rem;
}

.display {
  grid-row: 1;
  border: 1px solid #fff;
  height: 3.5rem;
  background: #0c2d48;
  display: grid;
  align-content: center;
  justify-content: end;
  font-size: 2rem;
  overflow: hidden;
  padding-right: .5rem;
}

.buttons {
  grid-row: 2;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: .5rem;
}

.btn {
  font: inherit;
  color: inherit;
  outline: none;
  border: 1px solid #fff;
  border: 1px solid #084171;
  background: #073052;
  padding: .25rem;
}

.num {
  background: none;
  border: 1px solid #073052;
}

.btn:hover {
  border-color: #10558e;
}

.equals {
  background: #007780;
}

              
            
!

JS

              
                const buttonMap = [
    {
        content: '(',
        id: 'left-paren',
    },{
        content: ')',
        id: 'right-paren',
    },{
        content: '%',
        id: 'percent',
    },{
        content: 'C',
        id: 'clear',
    },{
        content: '7',
        id: 'seven',
    },{
        content: '8',
        id: 'eight',
    },{
        content: '9',
        id: 'nine',
    },{
        content: '÷',
        id: 'divide',
    },{
        content: '4',
        id: 'four',
    },{
        content:'5',
        id: 'five',
    },{
        content: '6',
        id: 'six',
    },{
        content: 'x',
        id: 'multiply',
    },{
        content: '1',
        id: 'one',
    },{
        content: '2',
        id: 'two',
    },{
        content: '3',
        id: 'three',
    },{
        content: '-',
        id: 'subtract',
    },{
        content: '0',
        id: 'zero',
    },{
        content: '.',
        id: 'decimal',
    },{
        content: '=',
        id: 'equals',
    },{
        content: '+',
        id: 'add',
    }
];

const Buttons = (props) => {
    const buttons = buttonMap.map(obj => <Button key={obj.content} id={obj.id} handleClick={props.handleClick} evaluate={props.evaluate} clear={props.clear} content={obj.content} />)
    return (
        <div className="buttons">
            {buttons}
        </div>
    )
}

const Button = (props) => {
    return (
        <button
        id={props.id}
        className="btn"
        onClick={props.content === '=' ? props.evaluate : props.content === 'C' ? props.clear : props.handleClick} >
            {props.content}
        </button>
    )
}

const Display = (props) => {
    console.log(props.output);
    return (
        <div id="display" className="display" dangerouslySetInnerHTML={{ __html: props.output }} />
    )
}

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

        this.state = {
            calculation: '',
            output: '0',
            isEvaluated: false,
        };

        this.handleClick = this.handleClick.bind(this);
        this.clearDisplay = this.clearDisplay.bind(this);
        this.parseCalculationString = this.parseCalculationString.bind(this);
        this.calculate = this.calculate.bind(this);
        this.evaluate = this.evaluate.bind(this);
    }

    handleClick(e) {
        const char = e.target.innerText;
        const numArr = this.state.calculation.split(/[()%÷x\-+]/);
        const ops = '%÷x-+';
        let temp = '';

        if (char === '.') {
            if (numArr[numArr.length -1].includes('.')) {
                return;
            } else if (this.state.isEvaluated) {
                this.clearDisplay();
                temp = char;
            } else {
                temp = char;
            }
        } else if (ops.indexOf(char) > -1) {
            if ((this.state.calculation.length < 1) && (char !== '-')) {
                temp = '';
            } else if ((char === '%') && (this.state.calculation[this.state.calculation.length -1] === '%')) {
                temp = '';
            } else if (this.state.calculation[this.state.calculation.length - 1].match(/[0-9)%]/) != null) {
                temp = char;
            } else {
                if (char === '-') {
                    if (ops.includes(this.state.calculation[this.state.calculation.length -2])) {
                        temp = '';
                    } else {
                        temp = char;
                    }
                } else {
                    if (ops.indexOf(this.state.calculation[this.state.calculation.length-2]) > -1) {
                        return this.setState({
                            calculation: this.state.calculation.slice(0,-2) + char,
                            output: this.state.output.slice(0,-2) + char,
                        })
                    }
                    return this.setState({
                        calculation: this.state.calculation.slice(0,-1) + char,
                        output: this.state.output.slice(0,-1) + char,
                    });
                }
            }
        } else if ((char === '(') && (this.state.calculation === '')) {
            temp = char;
        }
        else if (((char === '(') && (this.state.calculation[this.state.calculation.length -1].match(/[0-9]/) != null )) ||
                   ((char.match(/[0-9]/) != null) && (this.state.calculation[this.state.calculation.length -1] === '%'))) {
            temp = `x${char}`;
        } else if ((char.match(/[0-9]/) != null) && (this.state.isEvaluated)) {
            return this.setState({
                calculation: char,
                output: char,
                isEvaluated: false,
            });
        } else {
            temp = char;
        }
        this.setState({
            calculation: this.state.calculation + temp,
            output: this.state.output === '0' ? temp : this.state.output + temp,
            isEvaluated: false,
        });
    }

    parseCalculationString(s) {
        const calculation = [];
        let current = '';

        for (let i = 0, ch; ch = s.charAt(i); i++) {
            if ('x÷+-'.indexOf(ch) > -1) {
                if (current === '' && ch === '-') {
                    current = '-';
                } else if (current === '') {
                    calculation.push(ch);
                } else {
                    calculation.push(new Decimal(current), ch);
                    current = '';
                }
            } else if ('()'.indexOf(ch) > -1) {
                ')'.indexOf(ch) > -1 ? (calculation.push(new Decimal(current), ch), current = '') : calculation.push(ch);
            } else {
                current += s.charAt(i);
            }
        }
        if (current !== '') {
            calculation.push(new Decimal(current));
        }
        return calculation;
    }

    calculate(calc) {
        const ops = [{'^': (a, b) => a.pow(b)},
            {'x': (a, b) => a.mul(b), '÷': (a, b) => a.div(b)},
            {'+': (a, b) => a.add(b), '-': (a, b) => a.sub(b)}];
        let newCalc = [],
            currentOp;
        for (let i = 0; i < ops.length; i++) {
            for (let j = 0; j < calc.length; j++) {
            if (calc[j] === '(') {
                newCalc.push(this.calculate(calc.slice(j+1, calc.lastIndexOf(')'))));
                j += calc.lastIndexOf(')') - j;
            } else if (ops[i][calc[j]]) {
                currentOp = ops[i][calc[j]];
            } else if (currentOp) {
                newCalc[newCalc.length - 1] = currentOp(newCalc[newCalc.length - 1], calc[j]);
                currentOp = null;
            } else {
                newCalc.push(calc[j]);
            }
            }
            calc = newCalc;
            newCalc = [];
        }
        if (calc.length > 1) {
            console.log('Error: unable to resolve calculation');
            return calc;
        } else {
            console.log(calc[0].toDP(10));
            return calc[0].toDP(10);
        }
    }

    evaluate() {
        const ops = '÷x-+';
        if (ops.indexOf(this.state.calculation[this.state.calculation.length-1]) > -1) return;
        this.setState({
            calculation: `(${this.state.calculation})`,
            isEvaluated: true,
            output: this.calculate(this.parseCalculationString(this.state.calculation.replace('%','÷100')))
        })
    }

    clearDisplay() {
        this.setState({
            calculation: '',
            output: '0',
        })
    }
    
    render() {
        return (
            <div className="calculator">
                <Display output={this.state.output} />
                <Buttons handleClick={this.handleClick} evaluate={this.evaluate} clear={this.clearDisplay} />
            </div>
        )
    }
}

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

Console