-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
110 lines (103 loc) · 2.38 KB
/
index.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// index.js
const resultDisplay = document.querySelector('.result');
const buttons = document.querySelectorAll('.btn');
let currentValue = '0';
let firstOperand = null;
let secondOperand = null;
let currentOperator = null;
let shouldClearDisplay = false;
function updateDisplay(value) {
resultDisplay.innerText = value;
}
function clearAll() {
currentValue = '0';
firstOperand = null;
secondOperand = null;
currentOperator = null;
updateDisplay(currentValue);
}
function appendNumber(number) {
if (currentValue === '0' || shouldClearDisplay) {
currentValue = number;
shouldClearDisplay = false;
} else {
currentValue += number;
}
updateDisplay(currentValue);
}
function setOperator(operator) {
if (currentOperator !== null) {
calculate();
}
firstOperand = parseFloat(currentValue);
currentOperator = operator;
shouldClearDisplay = true;
}
function calculate() {
if (currentOperator === null) {
return;
}
secondOperand = parseFloat(currentValue);
let result;
switch (currentOperator) {
case '+':
result = firstOperand + secondOperand;
break;
case '-':
result = firstOperand - secondOperand;
break;
case '*':
result = firstOperand * secondOperand;
break;
case '/':
if (secondOperand === 0) {
clearAll();
updateDisplay('Error');
return;
}
result = firstOperand / secondOperand;
break;
default:
return;
}
currentValue = result.toString();
updateDisplay(currentValue);
firstOperand = result;
secondOperand = null;
}
buttons.forEach(button => {
button.addEventListener('click', () => {
const value = button.innerText;
switch (value) {
case 'AC':
clearAll();
break;
case '+/-':
currentValue = (-parseFloat(currentValue)).toString();
updateDisplay(currentValue);
break;
case '%':
currentValue = (parseFloat(currentValue) / 100).toString();
updateDisplay(currentValue);
break;
case '+':
case '-':
case '*':
case '/':
setOperator(value);
break;
case '=':
calculate();
break;
case '.':
if (!currentValue.includes('.')) {
currentValue += '.';
updateDisplay(currentValue);
}
break;
default:
appendNumber(value);
break;
}
});
});