-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.js
101 lines (87 loc) · 2.82 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
100
101
class Calculator {
constructor() {
this.firstFactor = '0';
this.secondFactor;
this.operation;
this.screen = document.getElementById('display');
}
add(num1, num2) {
return Number(num1) + Number(num2);
}
subtract(num1, num2) {
return Number(num1) - Number(num2);
}
multiply(num1, num2) {
return Number(num1) * Number(num2);
}
divide(num1, num2) {
return Number(num1) / Number(num2);
}
handleOperation() {
let result;
// operations are based on the first operand if only one operand has been entered when hitting equal sign
this.secondFactor = this.secondFactor || this.firstFactor;
switch (this.operation) {
case '+':
result = this.add(this.firstFactor, this.secondFactor);
break;
case '-':
result = this.subtract(this.firstFactor, this.secondFactor);
break;
case 'x':
result = this.multiply(this.firstFactor, this.secondFactor);
break;
case '÷':
result = this.divide(this.firstFactor, this.secondFactor);
break;
default:
// fallback in case user hits equal without choosing an operator
result = this.screen.textContent;
}
calculator.firstFactor = result; // set first operand with previous operation's result
calculator.secondFactor = null;
this.screen.textContent = !result || result === Infinity ? 'Math ERROR' : result;
}
addNumber(input) {
if (this.checkError()) return;
if (!this.operation) {
this.screen.textContent = this.firstFactor === '0' ? input : this.screen.textContent + input;
this.firstFactor = this.screen.textContent;
} else {
this.screen.textContent =
!this.secondFactor || this.secondFactor === '0' ? input : this.screen.textContent + input;
this.secondFactor = this.screen.textContent;
}
}
addDecimal() {
if (this.checkError()) return;
if (this.operation) {
!this.secondFactor
? (this.screen.textContent = '0.')
: !this.screen.textContent.includes('.')
? (this.screen.textContent += '.')
: '';
this.secondFactor = this.screen.textContent;
} else {
!this.screen.textContent.includes('.') ? (this.screen.textContent += '.') : '';
this.firstFactor = this.screen.textContent;
}
}
clear() {
display.textContent = '0';
calculator.firstFactor = '0';
calculator.secondFactor = null;
calculator.operation = null;
}
delete() {
if (this.checkError()) return;
this.screen.textContent =
this.screen.textContent.length > 1 ? this.screen.textContent.slice(0, -1) : '0';
this.operation
? (this.secondFactor = this.screen.textContent)
: (this.firstFactor = this.screen.textContent);
}
checkError() {
return this.firstFactor === Infinity || isNaN(Number(this.firstFactor));
}
}