-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
193 lines (167 loc) · 4.97 KB
/
Copy pathapp.js
File metadata and controls
193 lines (167 loc) · 4.97 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
const calculator = document.querySelector(".calculator");
// Calculator script: comments cleaned. Code behavior unchanged.
const display = document.querySelector("#display");
let currentInput = "";
// Keep keyboard-focus helper commented out by default. Uncomment to focus
// the calculator container automatically on page load.
// window.addEventListener('load', () => calculator && calculator.focus());
// Main click handler: use event delegation from the calculator container.
// Buttons have class "button" and their `value` attribute holds the token.
calculator.addEventListener("click", (event) => {
const target = event.target;
if (target.classList.contains("button")) {
// Delete: remove last character
if (target.value === "del") {
currentInput = currentInput.slice(0, -1);
display.value = currentInput;
return;
}
// AC: clear all
if (target.value === "ac") {
currentInput = "";
display.value = currentInput;
return;
}
// Percentage: apply percent logic
if (target.value === "%") {
handlePercentage();
return;
}
// Default: append button value to input and update display
currentInput += target.value;
display.value = currentInput;
// If user typed '=' as part of the input, evaluate immediately
if (currentInput.includes("=")) {
performCalculation();
}
}
});
// -- Percentage --
function handlePercentage() {
if (!currentInput) return;
// remove any trailing '=' and trim
const input = currentInput.replace(/=.*$/, "").trim();
// find last operator index (ignore a leading minus as sign)
let lastOpIndex = -1;
for (let i = input.length - 1; i > 0; i--) {
if (/[+\-*/]/.test(input[i])) {
lastOpIndex = i;
break;
}
}
// if there's no operator, just divide the whole number by 100
if (lastOpIndex === -1) {
const n = parseFloat(input);
if (Number.isNaN(n)) return;
currentInput = String(n / 100);
display.value = currentInput;
return;
}
const op = input[lastOpIndex];
const left = input.slice(0, lastOpIndex);
const right = input.slice(lastOpIndex + 1);
if (right === "") return;
const num = parseFloat(right);
if (Number.isNaN(num)) return;
let percentValue;
if (op === "+" || op === "-") {
// for + or - treat percentage as (previousNumber * num / 100)
const m = left.match(/(-?\d+\.?\d*)\s*$/);
const prev = m ? parseFloat(m[1]) : 0;
percentValue = (prev * num) / 100;
} else {
// for * or / treat percentage as num / 100
percentValue = num / 100;
}
currentInput = left + op + String(percentValue);
display.value = currentInput;
}
// Perform the calculation using the current input expression.
function performCalculation() {
try {
let expression = currentInput.replace("=", "").trim(); // Remove the "=" at the end
if (expression === "") return;
let result = Function('"use strict"; return (' + expression + ")")();
currentInput = String(result);
saveToHistory(expression, result);
display.value = currentInput;
} catch (error) {
display.value = "Error";
currentInput = "";
}
}
// -- History --
let history = [];
function saveToHistory(expression, result) {
history.push(`${expression} = ${result}`);
console.log(history.length);
if (history.length > 4) {
history.shift();
}
updateHistoryDisplay();
}
function updateHistoryDisplay() {
const historylist = document.getElementById("historyList");
historylist.innerHTML = "";
history.forEach((item) => {
const li = document.createElement("li");
li.textContent = item;
historylist.appendChild(li);
});
}
// Show/Hide History
const historyBtn = document.getElementById("history-btn");
const historySidebar = document.getElementById("historySidebar");
historyBtn.addEventListener("click", function toggleHistory() {
historySidebar.style.display =
historySidebar.style.display === "none" ? "block" : "none";
});
// Use close Button
const closeHistoryBtn = document.getElementById("closeHistory");
closeHistoryBtn.addEventListener("click", function closeHistory() {
historySidebar.style.display = "none";
});
// Clear History
const clearHistoryBtn = document.getElementById("clearHistory");
clearHistoryBtn.addEventListener("click", function clearHistory() {
history = [];
updateHistoryDisplay();
});
// Keyboard Listener
window.addEventListener("keydown", function (event) {
if (event.key === "=" || event.key === "Enter") {
performCalculation();
return;
}
if (event.key == "Backspace") {
currentInput = currentInput.slice(0, -1);
display.value = currentInput;
return;
}
if (event.key == "Delete" || event.key == "Escape") {
currentInput = "";
display.value = currentInput;
return;
}
const validKeys = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"-",
"+",
"/",
"*",
".",
];
if (validKeys.includes(event.key)) {
currentInput += event.key;
display.value = currentInput;
}
});