-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
117 lines (94 loc) · 3.13 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
const display = document.querySelector(".container__display");
const keys = document.querySelector(".container__buttons");
const backspaceBtn = document.querySelector(".fa-backspace");
let displayContent;
let firstNumber;
let secondNumber;
let operator;
let previousKeyCategory;
keys.addEventListener("click", (event) => {
if (event.target.tagName === "BUTTON") {
const clickedBtnContent = event.target.textContent;
if (!isNaN(clickedBtnContent) && clickedBtnContent !== "") {
if (
display.innerText === "0" ||
previousKeyCategory === "operator"
) {
display.innerText = clickedBtnContent;
} else {
display.innerText += clickedBtnContent;
}
if (firstNumber) secondNumber = display.innerText;
previousKeyCategory = "number";
}
if (
clickedBtnContent === "+" ||
clickedBtnContent === "-" ||
clickedBtnContent === "×" ||
clickedBtnContent === "÷"
) {
if (
firstNumber &&
secondNumber &&
previousKeyCategory !== "equals"
) {
display.innerText = operate(
Number(firstNumber),
Number(secondNumber),
operator
);
}
operator = clickedBtnContent;
firstNumber = display.innerText;
previousKeyCategory = "operator";
}
if (clickedBtnContent === "=") {
if (!firstNumber) {
return;
}
if (!secondNumber) {
secondNumber = firstNumber;
}
display.innerText = operate(
Number(firstNumber),
Number(secondNumber),
operator
);
firstNumber = display.innerText;
previousKeyCategory = "equals";
}
if (clickedBtnContent === "AC") {
display.textContent = "0";
firstNumber = 0;
secondNumber = 0;
operator = "";
previousKeyCategory = "clear";
}
if (clickedBtnContent === ".") {
if (!display.innerText.includes(".")) {
display.innerText += ".";
}
if (previousKeyCategory === "operator") {
display.innerText = "0.";
}
previousKeyCategory = "decimal";
}
if (event.target === backspaceBtn) {
if (display.innerText.length > 1)
display.innerText = display.textContent.slice(0, -1);
else display.innerText = "0";
previousKeyCategory = "backspace";
}
}
});
function operate(x, y, operator) {
let result;
if (operator === "÷" && secondNumber === "0") {
return "0";
}
if (operator === "+") result = x + y;
else if (operator === "-") result = x - y;
else if (operator === "×") result = x * y;
else if (operator === "÷") result = x / y;
return +(Math.round(result + "e+7") + "e-7");
}