-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
65 lines (59 loc) · 1.76 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
const output = document.getElementById("output");
const form = document.getElementById("calc_form");
const operand_btns = document.querySelectorAll("button[data-type=operand]");
const operator_btns = document.querySelectorAll("button[data-type=operator]");
form.addEventListener("submit", (e) => {
e.preventDefault();
});
let is_operator = false;
let equation = [];
const remove_active = () => {
operator_btns.forEach((btn) => {
btn.classList.remove("active");
});
};
operand_btns.forEach((btn) => {
btn.addEventListener("click", (e) => {
remove_active();
if (output.value == "0") {
output.value = e.target.value;
} else if (is_operator) {
is_operator = false;
output.value = e.target.value;
} else if (output.value.includes(".")) {
output.value = output.value + "" + e.target.value.replace(".", "");
} else {
output.value = output.value + "" + e.target.value;
}
});
});
operator_btns.forEach((btn) => {
btn.addEventListener("click", (e) => {
remove_active();
e.currentTarget.classList.add("active");
switch (e.target.value) {
case "%":
output.value = parseFloat(output.value) / 100;
break;
case "invert":
output.value = parseFloat(output.value) * -1;
break;
case "=":
equation.push(output.value);
output.value = eval(equation.join(""));
equation = [];
break;
default:
let last_item = equation[equation.length - 1];
if (["/", "*", "+", "-"].includes(last_item) && is_operator) {
equation.pop();
equation.push(e.target.value);
} else {
equation.push(output.value);
equation.push(e.target.value);
}
is_operator = true;
break;
}
});
});