-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
185 lines (168 loc) · 5.62 KB
/
script.js
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
// Get references to HTML elements
const themeToggle = document.getElementById("themeToggle");
const equal = document.querySelector("#equal");
const form = document.querySelector("form");
const display = document.getElementById("display");
const buttons = document.querySelector(".buttons");
const resultEL = document.querySelector(".result");
const body = document.body;
const root = document.documentElement;
// Initialize variables
let result = ""; // Stores the current mathematical expression
let current = ""; // Stores the current user input
let inputDisplay = ""; // Displays the user input and result
let evaluation = false; // Flag to indicate if an evaluation is in progress
let basicOperations = { "+": "+", "/": "/", "*": "*", "-": "-" }; // Basic arithmetic operations
// Set a CSS variable to match the width of the result element
root.style.setProperty("--width-to-match", `${resultEL.clientWidth}px`);
// Theme toggle functionality
const theme = (theme, inverse = theme === "dark" ? "light" : "dark") => {
themeToggle.checked = theme === "dark" ? true : false;
body.classList.remove(`${inverse}-theme`);
body.classList.add(`${theme}-theme`);
localStorage.setItem("theme", `${theme}-theme`);
};
function themeSwitch() {
if (this.checked === true) theme("dark");
else theme("light");
}
themeToggle.addEventListener("click", themeSwitch);
// Retrieve saved theme from local storage
const savedTheme = localStorage.getItem("theme");
if (savedTheme) {
body.classList.add(savedTheme);
if (savedTheme === "dark-theme") theme("dark");
else theme("light");
}
// Handle Enter key to trigger evaluation
form.addEventListener("keypress", function (e) {
if (e.key === "Enter") {
e.preventDefault();
equal.click();
}
});
// Function to format numbers with a digit threshold
function formatted(number, digitThreshold = 10) {
const digitCount = `${number}`.replace(/^0+|\.+/g, "").length;
if (digitCount > digitThreshold) {
return number.toExponential(7).replace("+", "");
} else {
return number.toLocaleString();
}
}
// Event listener for button clicks
buttons.addEventListener("click", (e) => {
//handle equal button
if (e.target.value === "=") {
//check for basic operations in the result
Object.keys(basicOperations).forEach((n) => {
if (result.split("").includes(n)) {
if (basicOperations.hasOwnProperty(result.at(-1)) && current) {
evaluation = true;
result += current.replace(/^0+(?!\.)/, "") || "0";
inputDisplay = isNaN(formatted(eval(result)))
? `Bad Expression`
: "= " + `${formatted(eval(result))}`;
current = "";
}
}
});
}
// Handle clear button click
if (e.target.value === "C") {
inputDisplay = result = current = "";
evaluation = false;
}
// Handle backspace button click
if (e.target.value === "DEL") {
current = current.toString().slice(0, -1);
inputDisplay = formatted(+current);
}
// Handle square root, percentage, and plus/minus button clicks
if (
(e.target.value === "√" ||
e.target.value === "%" ||
e.target.value === "±") &&
inputDisplay !== "" &&
inputDisplay !== "0" &&
!/^0+$/.test(current)
) {
if (evaluation === true) {
current = `${eval(result)}`;
evaluation = false;
}
if (
result.split("").includes(e.target.value) ||
!basicOperations.hasOwnProperty(result.at(-1))
) {
result =
e.target.value === "%"
? current.replace(/^0+(?!\.)/, "") + e.target.value
: e.target.value + current.replace(/^0+(?!\.)/, "");
current =
e.target.value === "√"
? `${formatted(Math.sqrt(eval(current.replace(/^0+(?!\.)/, ""))))}`
: e.target.value === "%"
? `${formatted(eval(current.replace(/^0+(?!\.)/, "") / 100))}`
: `${formatted(eval(-current.replace(/^0+(?!\.)/, "")))}`;
inputDisplay = isNaN(current) ? `Bad Expression` : `= ` + current;
}
}
// Handle number button clicks
if (!isNaN(+e.target.value)) {
if (
result.split("").includes("√") ||
result.split("").includes("%") ||
result.split("").includes("±")
) {
current = result = "";
}
if (result && basicOperations.hasOwnProperty(result.at(-1))) {
inputDisplay = current;
evaluation = false;
}
if (evaluation === true) {
result = current;
}
current += e.target.value;
inputDisplay = formatted(+current);
evaluation = false;
}
// Handle basic operation button clicks
if (e.target.classList.contains("b-operators")) {
if (
result.split("").includes("√") ||
result.split("").includes("%") ||
result.split("").includes("±")
) {
result = "";
}
if (eval(current.replace(/^0+(?!\.)/, "") || "0") != "0") {
result +=
(current.replace(/^0+(?!\.)/, "") || "0") +
`${e.target.dataset.operation}`;
current = "";
}
if (result && !basicOperations.hasOwnProperty(result.at(-1))) {
result += `${e.target.dataset.operation}`;
}
if (basicOperations.hasOwnProperty(result.at(-1))) {
result = result.slice(0, -1) + `${e.target.dataset.operation}`;
}
}
// Handle dot button click
if (e.target.value === ".") {
if (current === "") {
inputDisplay = current = 0 + e.target.value;
}
if (!current.includes(".")) {
inputDisplay += ".";
current += ".";
}
}
// Update result and display
resultEL.textContent = result.replace(/^0+(?!\.)/, "");
display.value = inputDisplay.startsWith(".")
? "0" + inputDisplay.replace(/^0+(?!\.)/, "")
: inputDisplay.replace(/^0+(?!\.)/, "");
});