-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalc.js
105 lines (96 loc) · 2.57 KB
/
calc.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
console.log(
"Javascript Calculator Made by Ayush Vaishy\nhttps://github.com/AyushVaishy"
);
let flag = 0;
function isNumber(char) {
return /^\d$/.test(char);
}
document.getElementById("answer").readOnly = true;
let screen = document.getElementById("answer");
buttons = document.querySelectorAll("button");
let screenValue = "";
let lastScreenValue = "";
let maxItems = 6;
let isSign = true;
for (item of buttons) {
item.addEventListener("click", (e) => {
buttonText = e.target.innerText;
if (buttonText == "X" && !isSign) {
if (flag == 1) {
flag = 0;
}
buttonText = "*";
isSign = true;
screenValue += buttonText;
screen.value = screenValue;
} else if (buttonText == "C") {
if (flag == 1) {
flag = 0;
}
screenValue = "";
screen.value = screenValue;
screen.classList.remove("negative"); // Remove negative class
isSign = true;
} else if (buttonText == "=") {
checkForBracketMulti();
if (parseFloat(screen.value) < 0) {
screen.classList.add("negative");
} else {
screen.classList.remove("negative");
}
} else if(buttonText=="(" || buttonText==")") {
if(flag==1){
flag =0;
}
screenValue+=buttonText;
screen.value=screenValue;
}
else if (isNumber(buttonText)) {
if (flag == 1) {
screenValue = buttonText;
flag = 0;
} else {
screenValue += buttonText;
}
screen.value = screenValue;
isSign = false;
screen.classList.remove("negative"); // Remove negative class
} else {
if (flag == 1) {
flag = 0;
}
if (!isSign) {
screenValue = screen.value + buttonText;
screen.value = screenValue;
isSign = true;
}
screen.classList.remove("negative"); // Remove negative class
}
});
}
document.addEventListener("keydown", function (event) {
// ... (same code as before)
});
window.onerror = function () {
alert("PLEASE INPUT VALID EXPRESSION");
screenValue = "";
screen.value = screenValue;
screen.classList.remove("negative"); // Remove negative class
console.clear();
};
// ... (same code as before)
function checkForBracketMulti() {
// ... (same code as before)
if (eval(screenValue) !== undefined) {
screen.value = eval(screenValue);
lastScreenValue = screenValue;
screenValue = screen.value;
if (parseFloat(screen.value) < 0) {
screen.classList.add("negative");
} else {
screen.classList.remove("negative");
}
// ... (same code as before)
}
flag = 1;
}