-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
88 lines (78 loc) · 2.18 KB
/
script.js
File metadata and controls
88 lines (78 loc) · 2.18 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
let currentInput = "";
let operator = null;
let previousInput = "";
let history = [];
function appendNumber(number) {
currentInput += number;
updateDisplay();
}
function appendDot() {
if (!currentInput.includes(".")) {
currentInput += ".";
updateDisplay();
}
}
function setOperation(op) {
if (currentInput === "") return;
if (previousInput !== "") calculateResult();
operator = op;
previousInput = currentInput;
currentInput = "";
}
function clearDisplay() {
currentInput = "";
previousInput = "";
operator = null;
updateDisplay();
}
function backspace() {
currentInput = currentInput.slice(0, -1);
updateDisplay();
}
function sqrt() {
if (currentInput === "") return;
currentInput = Math.sqrt(parseFloat(currentInput)).toString();
addToHistory(`√(${currentInput})`);
updateDisplay();
}
function calculateResult() {
if (previousInput === "" || currentInput === "") return;
const prev = parseFloat(previousInput);
const current = parseFloat(currentInput);
let result;
switch (operator) {
case "+": result = prev + current; break;
case "-": result = prev - current; break;
case "*": result = prev * current; break;
case "/": result = current === 0 ? "Error" : prev / current; break;
case "%": result = prev % current; break;
default: return;
}
addToHistory(`${previousInput} ${operator} ${currentInput} = ${result}`);
currentInput = result.toString();
operator = null;
previousInput = "";
updateDisplay();
}
function updateDisplay() {
document.getElementById("display").value = currentInput;
}
function addToHistory(entry) {
history.unshift(entry);
const list = document.getElementById("historyList");
list.innerHTML = "";
history.forEach(item => {
const li = document.createElement("li");
li.textContent = item;
list.appendChild(li);
});
}
// Keyboard support
document.addEventListener("keydown", (e) => {
if (!isNaN(e.key)) appendNumber(e.key);
else if (["+", "-", "*", "/", "%"].includes(e.key)) setOperation(e.key);
else if (e.key === "Enter") calculateResult();
else if (e.key === "Backspace") backspace();
else if (e.key === "Escape") clearDisplay();
else if (e.key === ".") appendDot();
});