-
Notifications
You must be signed in to change notification settings - Fork 1
/
script.js
67 lines (59 loc) · 1.93 KB
/
script.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
const display = document.getElementById('display');
const buttons = document.querySelectorAll('.btn');
const clearButton = document.getElementById('clear');
const equalsButton = document.getElementById('equals');
let currentInput = '';
let operator = '';
let result = '';
buttons.forEach(button => {
button.addEventListener('click', () => handleButtonClick(button.textContent));
});
clearButton.addEventListener('click', clearDisplay);
equalsButton.addEventListener('click', performCalculation);
function handleButtonClick(value) {
if (value >= '0' && value <= '9') {
currentInput += value;
} else if (value === '.' && !currentInput.includes('.')) {
currentInput += value;
} else if (value === 'C') {
clearDisplay();
} else if (value === '=') {
performCalculation();
operator = '';
} else {
if (currentInput !== '') {
if (operator !== '') {
performCalculation();
} else {
result = currentInput;
}
operator = value;
currentInput = '';
}
}
display.value = `${result} ${operator} ${currentInput}`;
}
function performCalculation() {
if (currentInput !== '') {
if (operator === '+') {
result = (parseFloat(result) + parseFloat(currentInput)).toString();
} else if (operator === '-') {
result = (parseFloat(result) - parseFloat(currentInput)).toString();
} else if (operator === '*') {
result = (parseFloat(result) * parseFloat(currentInput)).toString();
} else if (operator === '/') {
result = (parseFloat(result) / parseFloat(currentInput)).toString();
} else {
result = currentInput;
}
}
currentInput = '';
operator = '';
display.value = result;
}
function clearDisplay() {
currentInput = '';
operator = '';
result = '';
display.value = '';
}