-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
67 lines (62 loc) · 2.14 KB
/
script.js
File metadata and controls
67 lines (62 loc) · 2.14 KB
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
// script.js
const display = document.querySelector(".display");
const buttons = document.querySelectorAll("button");
let currentInput = "";
let currentOperator = "";
let shouldClearDisplay = false;
buttons.forEach((button) => {
button.addEventListener("click", () => {
const buttonText = button.textContent;
if (buttonText.match(/[0-9.]/)) {
if (shouldClearDisplay) {
display.textContent = "";
shouldClearDisplay = false;
}
// Prevent multiple decimal points
if (buttonText === '.' && display.textContent.includes('.')) {
return;
}
display.textContent = display.textContent === '0' ? buttonText : display.textContent + buttonText;
} else if (buttonText === "C") {
display.textContent = "0";
currentInput = "";
currentOperator = "";
shouldClearDisplay = false;
} else if (buttonText === "=") {
if (currentOperator && currentInput) {
try {
const result = calculate(parseFloat(currentInput), currentOperator, parseFloat(display.textContent));
display.textContent = result.toString();
currentInput = result.toString();
currentOperator = "";
shouldClearDisplay = true;
} catch (error) {
display.textContent = "Error";
}
}
} else {
// Operator buttons
currentOperator = buttonText;
currentInput = display.textContent;
shouldClearDisplay = true;
}
});
});
function calculate(num1, operator, num2) {
switch (operator) {
case "+":
return num1 + num2;
case "-":
return num1 - num2;
case "*":
return num1 * num2;
case "/":
if (num2 !== 0) {
return num1 / num2;
} else {
throw new Error("Division by zero");
}
default:
return num2;
}
}