JS10 Day 9: Binary Calculator

개요[ | ]

JS10 Day 9: Binary Calculator
해커랭크 10 Days of Javascript
# 문제 비고
8-9 Day e
23 JS10 Day 8: Create a Button
24 JS10 Day 8: Buttons Container
25 JS10 Day 9: Binary Calculator

js/binaryCalculator.js
let res = document.getElementById("res");
function inputChar() {
    res.insertAdjacentHTML('beforeend',this.innerHTML);
}
document.getElementById("btn0").onclick = inputChar;
document.getElementById("btn1").onclick = inputChar;
document.getElementById("btnSum").onclick = inputChar;
document.getElementById("btnSub").onclick = inputChar;
document.getElementById("btnMul").onclick = inputChar;
document.getElementById("btnDiv").onclick = inputChar;
document.getElementById("btnClr").onclick = function() {
    res.innerHTML = "";
};
document.getElementById("btnEql").onclick = function() {
    let matched = res.innerHTML.match(/(\d+)([+\-\*\/])(\d+)/);
    let operand1 = parseInt(matched[1],2);
    let operator = matched[2];
    let operand2 = parseInt(matched[3],2);
    let result;
    switch( operator ) {
        case '+': result = operand1 + operand2; break;
        case '-': result = operand1 - operand2; break;
        case '*': result = operand1 * operand2; break;
        case '/': result = operand1 / operand2; break;
    }
    res.innerHTML = result.toString(2);
};
index.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" href="css/binaryCalculator.css" type="text/css">
        <title>Binary Calculator</title>
    </head>
    <body>
        <div id="res"></div>
        <div id="btns">
            <button id="btn0">0</button>
            <button id="btn1">1</button>
            <button id="btnClr">C</button>
            <button id="btnEql">=</button>
            <button id="btnSum">+</button>
            <button id="btnSub">-</button>
            <button id="btnMul">*</button>
            <button id="btnDiv">/</button>
        </div>
        <script src="js/binaryCalculator.js" type="text/javascript"></script>
    </body>
</html>
css/binaryCalculator.css
body {
    width: 33%;
}
#res {
    background-color: lightgray;
    border: solid;
    height: 48px;
    font-size: 20px;
}
#btn0, #btn1 {
    background-color: lightgreen;
    color: brown;
}
#btnClr, #btnEql {
    background-color: darkgreen;
    color: white;
}
#btnSum, #btnSub, #btnMul, #btnDiv {
    background-color: black;
    color: red
}
#btns button {
    width: 25%;
    height: 36px;
    font-size: 18px;
    margin: 0px;
    float: left;
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}