-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
61 lines (57 loc) · 1.8 KB
/
Copy pathapp.js
File metadata and controls
61 lines (57 loc) · 1.8 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
document.addEventListener("DOMContentLoaded", () => {
const display = document.getElementById("display");
const buttons = document.querySelectorAll(".btn");
let currentInput = "";
let operator = "";
let firstValue = "";
function updateDisplay(value) {
display.value = value;
}
buttons.forEach(btn => {
btn.addEventListener("click", () => {
const value = btn.innerText;
const action = btn.dataset.action;
if (btn.classList.contains("number")) {
currentInput += value;
updateDisplay(currentInput);
}
else if (btn.classList.contains("operator")) {
if (currentInput === "" && firstValue === "") return;
if (firstValue === "") {
firstValue = currentInput;
operator = action;
currentInput = "";
} else {
firstValue = eval(`${firstValue} ${operator} ${currentInput}`);
operator = action;
currentInput = "";
updateDisplay(firstValue);
}
}
else if (action === "=") {
if (firstValue !== "" && currentInput !== "") {
firstValue = eval(`${firstValue} ${operator} ${currentInput}`);
updateDisplay(firstValue);
currentInput = "";
operator = "";
}
}
else if (action === "clear") {
currentInput = "";
firstValue = "";
operator = "";
updateDisplay("");
}
else if (action === "back") {
currentInput = currentInput.slice(0, -1);
updateDisplay(currentInput);
}
else if (action === "+/-") {
if (currentInput !== "") {
currentInput = (parseFloat(currentInput) * -1).toString();
updateDisplay(currentInput);
}
}
});
});
});