-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalc.js
102 lines (86 loc) · 2.63 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
console.log(document.readyState);
console.log(performance.now());
document.addEventListener("readystatechange", () => {
if (document.readyState == "interactive") {
console.log(performance.now());
}
if (document.readyState == "complete") {
console.log(performance.now());
}
});
let operator = "";
let previousValue = "";
let currentValue = "";
document.addEventListener("DOMContentLoaded", () => {
const clearAll = document.querySelector("#key19");
const equal = document.querySelector("#key22");
const decimal = document.querySelector("#key21");
const numbers = document.querySelectorAll(".number");
const operators = document.querySelectorAll(".operator");
const previousScreen = document.querySelector(".previous");
const currentScreen = document.querySelector(".current");
numbers.forEach((number) => number.addEventListener("click", (e) => {
handleNumber(e.target.textContent);
currentScreen.textContent = currentValue;
}));
operators.forEach((op) => op.addEventListener("click", (e) => {
handleOperator(e.target.textContent);
previousScreen.textContent = `${previousValue} ${operator}`;
currentScreen.textContent = currentValue;
}));
clearAll.addEventListener("click", () => {
previousValue = "";
currentValue = "";
operator = "";
previousScreen.textContent = currentValue;
currentScreen.textContent = currentValue;
});
equal.addEventListener("click", () => {
if (currentValue != "" && previousValue != "") {
calculate();
previousScreen.textContent = "Result:";
if (previousValue.length <= 5) {
currentScreen.textContent = previousValue;
} else {
currentScreen.textContent = `${previousValue.slice(0, 7)}...`;
}
}
});
decimal.addEventListener("click", () => {
addDecimal();
});
});
function handleNumber(num) {
if (currentValue.length <= 5) {
currentValue += num;
}
}
function handleOperator(op) {
operator = op;
previousValue = currentValue;
currentValue = "";
}
function calculate() {
previousValue = Number(previousValue);
currentValue = Number(currentValue);
if (operator === "+") {
previousValue += currentValue;
} else if (operator === "-") {
previousValue -= currentValue;
} else if (operator === "X") {
previousValue *= currentValue;
} else {
previousValue /= currentValue;
}
previousValue = roundNumber(previousValue);
previousValue = previousValue.toString();
currentValue = previousValue.toString();
}
function roundNumber(num) {
return Math.round(num * 1000) / 1000;
}
function addDecimal() {
if (!currentValue.includes(".")) {
currentValue += ".";
}
}