-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
55 lines (52 loc) · 1.67 KB
/
Copy pathscript.js
File metadata and controls
55 lines (52 loc) · 1.67 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
const display = document.getElementById("display");
let expression = "";
const buttons = document.querySelectorAll("button");
buttons.forEach(button => {
button.addEventListener("click", () => {
const value = button.textContent;
if (value === "C") {
// Clear all
expression = "";
display.textContent = "0";
} else if (value === "=") {
// Calculate the expression
try {
const sanitized = expression.replace(/x/g, "*").replace(/÷/g, "/");
const result = eval(sanitized);
display.textContent = result;
expression = result.toString();
} catch (err) {
display.textContent = "Error";
expression = "";
}
} else if (value === "-/+") {
// Toggle sign
if (expression) {
if (expression.startsWith("-")) {
expression = expression.slice(1);
} else {
expression = "-" + expression;
}
display.textContent = expression;
}
} else if (value === "%") {
// Percentage
try {
const result = eval(expression) / 100;
display.textContent = result;
expression = result.toString();
} catch (err) {
display.textContent = "Error";
expression = "";
}
} else if (value === "←") {
// Backspace one digit
expression = expression.slice(0, -1);
display.textContent = expression || "0";
} else {
// Append normal number/operator
expression += value === "x" ? "*" : value;
display.textContent = expression.replace(/\*/g, "x");
}
});
});