-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
87 lines (79 loc) · 2.07 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
let displayInput = document.querySelector('.display input');
let currentOperator = null;
let firstOperand = null;
let secondOperand = null;
let result = null;
function handleNumberClick(number) {
if (displayInput.value === '0' || displayInput.value === '') {
displayInput.value = number;
} else {
displayInput.value += number;
}
}
function handleOperatorClick(operator) {
if (currentOperator === null) {
firstOperand = parseFloat(displayInput.value);
currentOperator = operator;
displayInput.value = '0';
} else {
secondOperand = parseFloat(displayInput.value);
calculate();
firstOperand = result;
currentOperator = operator;
displayInput.value = '0';
}
}
function handleOnclickClick(decimal) {
if (!displayInput.value.includes(decimal)) {
displayInput.value += decimal;
}
}
function calculate() {
secondOperand = parseFloat(displayInput.value);
switch (currentOperator) {
case '+':
result = firstOperand + secondOperand;
break;
case '-':
result = firstOperand - secondOperand;
break;
case '*':
result = firstOperand * secondOperand;
break;
case '/':
result = firstOperand / secondOperand;
break;
case '%':
result = firstOperand % secondOperand;
break;
default:
result = secondOperand;
}
displayInput.value = result.toString();
}
document.querySelectorAll('.number').forEach(button => {
button.addEventListener('click', () => handleNumberClick(button.textContent));
});
document.querySelectorAll('.operator').forEach(button => {
button.addEventListener('click', () => {
if (button.textContent === 'AC') {
clearCalculator();
} else if (button.textContent === 'C') {
clearDisplay();
} else if (button.textContent === '=') {
calculate();
} else {
handleOperatorClick(button.textContent);
}
});
});
function clearCalculator() {
displayInput.value = '0';
currentOperator = null;
firstOperand = null;
secondOperand = null;
result = null;
}
function clearDisplay() {
displayInput.value = '0';
}