-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathapp.js
More file actions
71 lines (60 loc) · 1.64 KB
/
app.js
File metadata and controls
71 lines (60 loc) · 1.64 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
let displayValue = "";
let memory = 0;
let history = [];
function appendNumber(number) {
displayValue += number;
updateDisplay();
}
function appendOperator(operator) {
if (displayValue === "") return;
if (isNaN(displayValue[displayValue.length - 1])) return;
displayValue += operator;
updateDisplay();
}
function appendFunction(func) {
displayValue = `${func}(${displayValue})`;
calculate();
}
function clearDisplay() {
displayValue = "";
updateDisplay();
}
function deleteLast() {
displayValue = displayValue.slice(0, -1);
updateDisplay();
}
function memoryStore() {
memory = parseFloat(displayValue) || 0;
updateDisplay();
}
function memoryRecall() {
displayValue += memory.toString();
updateDisplay();
}
function updateDisplay() {
document.getElementById("display").value = displayValue;
}
function calculate() {
try {
const result = eval(displayValue);
history.push(`${displayValue} = ${result}`);
displayValue = result.toString();
updateDisplay();
updateHistory();
} catch (error) {
displayValue = "Error";
updateDisplay();
setTimeout(clearDisplay, 1500);
}
}
function updateHistory() {
document.getElementById("history").textContent = history[history.length - 1] || "";
}
// Keyboard support
document.addEventListener("keydown", function (e) {
if (!isNaN(e.key)) appendNumber(e.key);
else if (['+', '-', '*', '/'].includes(e.key)) appendOperator(e.key);
else if (e.key === 'Enter') calculate();
else if (e.key === 'Backspace') deleteLast();
else if (e.key === 'Escape') clearDisplay();
});