-
Notifications
You must be signed in to change notification settings - Fork 966
Expand file tree
/
Copy pathindex.js
More file actions
81 lines (79 loc) · 2.89 KB
/
index.js
File metadata and controls
81 lines (79 loc) · 2.89 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
const display = document.querySelector("#display");
const buttons = document.querySelectorAll("button");
buttons.forEach((item) => {
item.onclick = () => {
if (item.id == "clear") {
display.innerText = "";
} else if (item.id == "backspace") {
let string = display.innerText.toString();
display.innerText = string.substr(0, string.length - 1);
} else if (display.innerText != "" && item.id == "equal") {
try {
// Division by zero validation
if (/\/(0+(?![0-9\.]))/.test(display.innerText)) {
throw new Error("Division by zero");
}
// Consecutive operators validation
if (/([+\-*/]{2,})/.test(display.innerText)) {
throw new Error("Consecutive operators");
}
// Multiple decimal points in a number validation
const tokens = display.innerText.split(/([+\-*/])/);
for (let token of tokens) {
if (token.split(".").length > 2) {
throw new Error("Multiple decimals in a number");
}
}
display.innerText = Function(
'"use strict";return (' + display.innerText + ")"
)();
} catch (e) {
let errorMsg = "Error!";
if (e.message === "Division by zero") {
errorMsg = "Cannot divide by zero!";
} else if (e.message === "Consecutive operators") {
errorMsg = "Invalid consecutive operators!";
} else if (e.message === "Multiple decimals in a number") {
errorMsg = "Invalid decimal usage!";
}
display.innerText = errorMsg;
setTimeout(() => (display.innerText = ""), 2000);
}
} else if (display.innerText == "" && item.id == "equal") {
display.innerText = "Empty!";
setTimeout(() => (display.innerText = ""), 2000);
} else {
const lastChar = display.innerText.slice(-1);
if (["+", "-", "*", "/"].includes(item.innerText)) {
// Prevent consecutive operators
if (
display.innerText === "" ||
["+", "-", "*", "/"].includes(lastChar)
) {
// Don't allow operator at start or after another operator
return;
}
display.innerText += item.innerText;
} else if (item.innerText === ".") {
// Prevent multiple decimals in a number
const parts = display.innerText.split(/([+\-*/])/);
const lastNum = parts[parts.length - 1];
if (lastNum.includes(".")) {
return;
}
display.innerText += item.innerText;
} else {
display.innerText += item.innerText;
}
}
};
});
const themeToggleBtn = document.querySelector(".theme-toggler");
const calculator = document.querySelector(".calculator");
const toggleIcon = document.querySelector(".toggler-icon");
let isDark = true;
themeToggleBtn.onclick = () => {
calculator.classList.toggle("dark");
themeToggleBtn.classList.toggle("active");
isDark = !isDark;
};