-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
199 lines (174 loc) · 5.05 KB
/
script.js
File metadata and controls
199 lines (174 loc) · 5.05 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
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
// State variables
let currentInput = "";
let calculationPerformed = false;
// DOM Elements
const displayInput = document.getElementById("input");
const buttons = document.querySelector(".buttons");
const themeSwitcher = document.getElementById("theme-switcher");
// --- THEME SWITCHER ---
const applyTheme = (theme) => {
document.body.setAttribute("data-theme", theme);
themeSwitcher.checked = theme === 'light';
localStorage.setItem("theme", theme);
};
themeSwitcher.addEventListener("change", () => {
applyTheme(themeSwitcher.checked ? 'light' : 'dark');
});
// Apply saved theme on load or default to dark
const savedTheme = localStorage.getItem("theme") || 'dark';
applyTheme(savedTheme);
// --- CALCULATOR LOGIC ---
const updateDisplay = () => {
displayInput.value = currentInput || "0";
};
const handleNumber = (value) => {
if (calculationPerformed) {
currentInput = "";
calculationPerformed = false;
}
currentInput += value;
};
const handleOperator = (value) => {
if (currentInput === "" && value !== "-") return;
calculationPerformed = false;
const lastChar = currentInput.slice(-1);
// Prevent multiple operators in a row, but allow for negative numbers
if (['+', '-', '*', '/'].includes(lastChar)) {
currentInput = currentInput.slice(0, -1);
}
currentInput += value;
};
const handleDecimal = () => {
if (calculationPerformed) {
currentInput = "0.";
calculationPerformed = false;
return;
}
const parts = currentInput.split(/[\+\-\*\/]/);
const lastPart = parts[parts.length - 1];
if (!lastPart.includes(".")) {
currentInput += ".";
}
};
const solve = () => {
if (currentInput === "") return;
try {
const sanitizedInput = currentInput.replace(/[^-\d/*+.]/g, '');
if (sanitizedInput !== currentInput) {
throw new Error("Invalid characters in input");
}
const result = new Function(`return ${sanitizedInput}`)();
currentInput = String(parseFloat(result.toPrecision(15)));
calculationPerformed = true;
} catch (err) {
currentInput = "Error";
calculationPerformed = true;
}
updateDisplay();
};
const clearInput = () => {
currentInput = "";
calculationPerformed = false;
updateDisplay();
};
const eraseLast = () => {
if (calculationPerformed) {
clearInput();
return;
}
currentInput = currentInput.slice(0, -1);
updateDisplay();
};
const calculatePercent = () => {
if (currentInput === "") return;
try {
const result = new Function(`return ${currentInput}`)() / 100;
currentInput = String(parseFloat(result.toPrecision(15)));
calculationPerformed = true;
} catch (err) {
currentInput = "Error";
calculationPerformed = true;
}
updateDisplay();
};
const calculateSquareRoot = () => {
if (currentInput === "" || currentInput === "Error") return;
try {
// First, evaluate the expression in the display
const value = new Function(`return ${currentInput}`)();
if (value < 0) {
currentInput = "Error"; // Can't take sqrt of a negative number
} else {
const result = Math.sqrt(value);
currentInput = String(parseFloat(result.toPrecision(15)));
}
calculationPerformed = true;
} catch (err) {
currentInput = "Error";
calculationPerformed = true;
}
updateDisplay();
};
// --- EVENT LISTENERS ---
buttons.addEventListener("click", (e) => {
const target = e.target.closest('button');
if (!target) return;
const value = target.dataset.value;
if (target.matches(".input-button")) {
if (value === ".") {
handleDecimal();
} else if (['+', '-', '*', '/'].includes(value)) {
handleOperator(value);
} else {
handleNumber(value);
}
} else {
switch (target.id) {
case "equal":
solve();
break;
case "clear":
clearInput();
break;
case "erase":
eraseLast();
break;
case "sqrt":
calculateSquareRoot();
break;
case "percent":
calculatePercent();
break;
}
}
if (target.id !== 'equal' && target.id !== 'percent' && target.id !== 'sqrt' && currentInput !== "Error") {
updateDisplay();
}
});
document.addEventListener("keydown", (e) => {
const key = e.key;
let handled = true;
if (/\d/.test(key)) {
handleNumber(key);
} else if (key === ".") {
handleDecimal();
} else if (['+', '-', '*', '/'].includes(key)) {
handleOperator(key);
} else if (key === "Enter" || key === "=") {
solve();
} else if (key === "Backspace") {
eraseLast();
} else if (key === "Escape" || key === "Delete") {
clearInput();
} else {
handled = false;
}
if (handled) {
e.preventDefault();
if (key !== 'Enter' && key !== '=' && currentInput !== "Error") {
updateDisplay();
}
}
});
// Initial display update
updateDisplay();