Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
73 lines (61 loc) · 1.53 KB
/
Copy pathscript.js
File metadata and controls
73 lines (61 loc) · 1.53 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
const clickSound = new Audio("click.mp3");
const display = document.getElementById("display");
function append(value) {
display.value += value;
}
function clearDisplay() {
display.value = "";
}
function deleteLast() {
display.value = display.value.slice(0, -1);
}
function calculate() {
try {
let result = display.value
.replace(/π/g, Math.PI) // Replace π with Math.PI
.replace(/×/g, "*") // Optional: in case user types ×
.replace(/÷/g, "/") // Optional: in case user types ÷
.replace(/%/g, "/100"); // Convert percent to division
display.value = eval(result);
} catch {
display.value = "Error";
}
}
// Keyboard Support
document.addEventListener("keydown", (e) => {
const allowedKeys = "0123456789/*-+.%().";
if (allowedKeys.includes(e.key)) {
append(e.key);
} else if (e.key === "Enter") {
calculate();
} else if (e.key === "Backspace") {
deleteLast();
} else if (e.key.toLowerCase() === "c") {
clearDisplay();
}
});
function append(value) {
clickSound.play();
display.value += value;
}
function clearDisplay() {
clickSound.play();
display.value = "";
}
function deleteLast() {
clickSound.play();
display.value = display.value.slice(0, -1);
}
function calculate() {
clickSound.play();
try {
let result = display.value
.replace(/π/g, Math.PI)
.replace(/×/g, "*")
.replace(/÷/g, "/")
.replace(/%/g, "/100");
display.value = eval(result);
} catch {
display.value = "Error";
}
}