-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.js
More file actions
105 lines (88 loc) · 2.46 KB
/
calculator.js
File metadata and controls
105 lines (88 loc) · 2.46 KB
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
class Calculator {
constructor(previousValue, currentValue) {
this.previousValue = previousValue;
this.currentValue = currentValue;
this.clear();
}
clear() {
this.currentOperand = "";
this.previousOperand = "";
this.operation = undefined;
}
delete() {
this.currentOperand = this.currentOperand.toString().slice(0, -1);
}
showNumber(number) {
if(number === "." && this.currentOperand.includes(".")) return
this.currentOperand = this.currentOperand + number.toString();
}
showOperations(operation) {
if (this.currentOperand === "") return
if (this.previousOperand !== "") {
this.calculate();
}
this.operation = operation;
this.previousOperand = this.currentOperand + " " + operation.toString();
this.currentOperand = "";
}
calculate() {
const current = parseFloat(this.currentOperand);
const previous = parseFloat(this.previousOperand);
let total;
switch (this.operation) {
case "+":
total = previous + current;
break;
case "-":
total = previous - current;
break;
case "÷":
total = previous / current;
break;
case "*":
total = previous * current;
break;
default:
return
}
this.currentOperand = total;
this.previousOperand = "";
}
updateDisplay() {
this.currentValue.innerText = this.currentOperand;
this.previousValue.innerText = this.previousOperand;
}
}
const numberBtn = document.querySelectorAll("[data-number]");
const operations = document.querySelectorAll("[data-operations]");
const equalBtn = document.querySelector("[data-equals]");
const deleteBtn = document.querySelector("[data-delete");
const clearBtn = document.querySelector("[data-all-clear]");
const previous = document.querySelector("[data-previous-value]");
const current = document.querySelector("[data-current-value]");
//Instantiate the Calculator class
const calculator = new Calculator(previous, current);
clearBtn.addEventListener("click", () => {
calculator.clear();
calculator.updateDisplay();
})
numberBtn.forEach(number => {
number.addEventListener("click", () => {
calculator.showNumber(number.innerText)
calculator.updateDisplay()
});
})
operations.forEach(operation => {
operation.addEventListener("click", () => {
calculator.showOperations(operation.innerText)
calculator.updateDisplay()
});
})
equalBtn.addEventListener("click", () => {
calculator.calculate()
calculator.updateDisplay()
});
deleteBtn.addEventListener("click", () => {
calculator.delete()
calculator.updateDisplay()
})