-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.js
99 lines (82 loc) · 1.86 KB
/
calculator.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
content = "0";
num1 = NaN;
num2 = NaN;
op = "";
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
function divide(a, b) {
return Math.floor(a / b);
}
function operate(operator, a, b) {
switch (operator) {
case "+":
return add(a, b);
case "-":
return subtract(a, b);
case "x":
return multiply(a, b);
case "÷":
return divide(a, b);
default:
return;
}
}
function numButton(e) {
input = e.target.innerText;
updateContent(input);
}
function updateContent(input) {
if (!isNaN(input)) {
if (content === "0") {
content = "";
}
content += input;
changeDisplay(content);
return;
}
else if (input === ".") {
console.log("TODO");
return;
}
else if (input === "=") {
num2 = parseInt(content);
res = operate(op, num1, num2);
num1 = NaN;
num2 = NaN;
content = toString(res);
changeDisplay(res);
}
else {
num1 = parseInt(content);
op = input;
clear();
}
}
function del() {
content = content.substring(0, content.length-1);
if (content === "") {
content = "0";
}
changeDisplay(content);
}
function clear() {
content = "0";
changeDisplay(content);
}
function changeDisplay(content) {
display = document.querySelector(".display");
display.innerText=content;
}
padButtons = document.querySelectorAll(".pad");
padButtons.forEach(padButton => padButton.addEventListener('click', numButton));
clearButton = document.querySelector(".clear");
clearButton.addEventListener('click', clear);
delButton = document.querySelector(".delete");
delButton.addEventListener('click', del);