-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-calculator.js
65 lines (61 loc) · 1.36 KB
/
binary-calculator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
let firstNumber = '';
let secondNumber = '';
let operation = '';
let result = '';
function clearDisplay() {
res.innerText = '';
}
function setDisplay(d) {
res.innerText = res.innerText + d;
}
function setOperation(o) {
firstNumber = res.innerText;
operation = o;
}
btn0.addEventListener('click', event => {
setDisplay(0);
});
btn1.addEventListener('click', event => {
setDisplay(1);
});
btnClr.addEventListener('click', event => {
clearDisplay();
});
btnSum.addEventListener('click', event => {
setOperation('sum');
setDisplay('+');
});
btnSub.addEventListener('click', event => {
setOperation('sub');
setDisplay('-');
});
btnMul.addEventListener('click', event => {
setOperation('mul');
setDisplay('*');
});
btnDiv.addEventListener('click', event => {
setOperation('div');
setDisplay('/');
});
btnEql.addEventListener('click', event => {
secondNumber = res.innerText.slice(firstNumber.length + 1);
clearDisplay();
switch (operation) {
case 'sum':
result = parseInt(firstNumber,2) + parseInt(secondNumber,2);
break;
case 'sub':
result = parseInt(firstNumber,2) - parseInt(secondNumber,2);
break;
case 'mul':
result = parseInt(firstNumber,2) * parseInt(secondNumber,2);
break;
case 'div':
result = parseInt(firstNumber,2) / parseInt(secondNumber,2);
break;
default:
clearDisplay();
break;
}
setDisplay(result.toString(2));
});