binary calculator
day 9 hackerRank
by trentHarlem
HTML
<div id='result'></div>
<!-- Contains the result of button presses. -->
<div id='btns'>
<!--A container displays all 8 calc buttons.-->
<button id='btn0'>0</button>
<!-- A button expressing binary digit 0.-->
<button id='btn1'>1</button>
<!--1 btn1 A button expressing binary digit 1.-->
<button id='btnClr'>C</button>
<!--C A button to clear the contents of .-->
<button id='btnEql'>=</button>
<!--= A button to evaluate the contents of the expression in .-->
<button id='btnSum'>+</button>
<!--+ A button for the addition operation.-->
<button id='btnSub'>-</button>
<!--- A button for the subtraction operation.-->
<button id='btnMul'>*</button>
<!--* A button for the multiplication operation.-->
<button id='btnDiv'>/</button>
<!--/ -->
</div>
CSS
body {
width: 33%;
}
#result {
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;
}
JavaScript
let res = document.getElementById("result");
btn0.onclick = function() {
res.innerHTML += "0";
}
btn1.onclick = function() {
res.innerHTML += "1";
}
btnSum.onclick = function() {
res.innerHTML += "+";
}
btnSub.onclick = function() {
res.innerHTML += "-";
}
btnMul.onclick = function() {
res.innerHTML += "*";
}
btnDiv.onclick = function() {
res.innerHTML += "/";
}
btnClr.onclick = function() {
res.innerHTML = "";
}
btnEql.onclick = function() {
let sol = res.innerHTML;
//sol = Math.floor(eval(sol.replace(/([01]+)/g, '0b$1'))).toString(2);
sol = Math.floor(eval(sol.replace(/([01]+)/g, '0b$1'))).toString(2);
res.innerHTML = sol;
}
// ////////////////
var opr = "";
var screen = document.getElementById("res");
screen.innerHTML = "";
function buttonClicked(e) {
console.log(e)
var btn = e.target || e.srcElement;
if (btn.id != "btnClr" && btn.id != "btnEql") {
screen.innerHTML += btn.innerHTML;
if (btn.id != "btn0" && btn.id != "btn1") {
opr = btn.innerHTML;
}
} else if (btn.id == "btnEql") {
var str = screen.innerHTML.split(opr);
var op1 = str[0];
var op2 = str[1];
/* The double bitwise NOT ('~~') is a shortcut for Math.floor() */
screen.innerHTML = (~~eval(parseInt(op1, 2) + opr + parseInt(op2, 2))).toString(2);
opr = "";
} else if (btn.id == "btnClr") {
screen.innerHTML = "";
opr = "";
}
}