-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
81 lines (81 loc) · 2.66 KB
/
app.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
window.onload = () => {
let inputs = [];
let operator = '';
const displayRes = () => {
const res = document.getElementById('res');
let val1 = inputs[0];
let val2 = inputs[1] === undefined ? '' : inputs[1];
res.innerText = `${val1}${operator}${val2}`;
};
const setOperator = op => {
if (inputs[1] === undefined) {
operator = op;
}
displayRes();
};
const setValues = num => {
if (inputs.length === 0) {
inputs[0] = num;
} else if (inputs.length === 1 && operator.length === 0) {
inputs[0] += num;
} else if (inputs.length === 1 && operator.length > 0) {
inputs[1] = num;
} else if (inputs.length === 2 && operator.length > 0) {
inputs[1] += num;
}
displayRes();
};
const btn0 = document.getElementById('btn0');
btn0.addEventListener('click', () => {
setValues('0');
});
const btn1 = document.getElementById('btn1');
btn1.addEventListener('click', () => {
setValues('1');
});
const btnSum = document.getElementById('btnSum');
btnSum.addEventListener('click', () => {
setOperator('+');
});
const btnSub = document.getElementById('btnSub');
btnSub.addEventListener('click', () => {
setOperator('-');
});
const btnMul = document.getElementById('btnMul');
btnMul.addEventListener('click', () => {
setOperator('*');
});
const btnDiv = document.getElementById('btnDiv');
btnDiv.addEventListener('click', () => {
setOperator('/');
});
const btnClr = document.getElementById('btnClr');
btnClr.addEventListener('click', () => {
inputs = [''];
operator = '';
displayRes();
});
const btnEql = document.getElementById('btnEql');
btnEql.addEventListener('click', () => {
if (inputs.length === 2 && operator.length > 0) {
let a = parseInt(inputs[0], 2);
let b = parseInt(inputs[1], 2);
switch (operator) {
case '+':
inputs = [(a + b).toString(2)];
break;
case '-':
inputs = [(a - b).toString(2)];
break;
case '*':
inputs = [parseInt(a * b, 0).toString(2)];
break;
case '/':
inputs = [parseInt(a / b, 0).toString(2)];
break;
}
operator = '';
displayRes();
}
});
};