-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
227 lines (202 loc) · 6.96 KB
/
script.js
File metadata and controls
227 lines (202 loc) · 6.96 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
'use strict';
// toggle theme
document.querySelector('#toggleTheme').addEventListener('change', () => {
document.body.classList.toggle('dark');
});
// calculator
const operations = {
add(num1, num2) {
return num1 + num2;
},
subtract(num1, num2) {
return num1 - num2;
},
multiply(num1, num2) {
return num1 * num2;
},
divide(num1, num2) {
return num1 / num2;
}
};
const operationSymbols = {
add: '+',
subtract: '-',
multiply: 'x',
divide: '/'
};
const round = num => {
let result = Math.round((num + Number.EPSILON) * 10000) / 10000;
if (result.toString().length > 12) {
result = result.toExponential(3);
}
return result;
};
class Calculator {
constructor(mainDisplay, operationDisplay) {
this.mainDisplay = mainDisplay;
this.operationDisplay = operationDisplay;
this.clear();
}
updateMainDisplay(str) {
this.mainDisplay.textContent = str;
}
updateOperationDisplay(str) {
this.operationDisplay.textContent = str;
}
clear() {
this.updateMainDisplay('0');
this.updateOperationDisplay('');
this.operationType = null;
this.num1 = null;
this.num2 = null;
this.operatorPressed = false;
this.currentNumberUpdated = false;
}
displayOperand(str) {
const displayStr = this.mainDisplay.textContent;
this.operatorPressed = false;
// Initial display = "0", replace it by the first operand, e.g. "2" or "0."
if (displayStr === '0') {
this.mainDisplay.textContent = str === '.' ? `0${str}` : str;
return;
}
// don't add "." if there's already one
if (str === '.' && displayStr.includes('.')) {
return;
}
// add numbers to the display if string length < 12, display limit: 12 numbers
if (displayStr.length < 12) this.mainDisplay.textContent += str;
}
isResultDisplayed() {
return this.mainDisplay.textContent.includes('=');
}
getDisplayedNumber() {
return +this.mainDisplay.textContent;
}
displayOperation(num1, operation, num2 = null) {
const operationDisplayed = `${num1}${operationSymbols[operation]}${
num2 ?? ''
}`;
this.updateOperationDisplay(operationDisplayed);
this.updateMainDisplay('0');
this.operatorPressed = true;
}
percentage() {
let displayStr = this.mainDisplay.textContent;
if (this.isResultDisplayed()) {
if (displayStr.includes('Error')) return;
// if there's a result on the display, get the result value and assign it to num1
displayStr = displayStr.replace('= ', '');
this.num1 = round(+displayStr / 100);
this.updateOperationDisplay('');
this.currentNumberUpdated = true;
}
this.updateMainDisplay(round(+displayStr / 100));
}
backspace() {
if (this.isResultDisplayed()) {
this.clear();
return;
}
const displayStr = this.mainDisplay.textContent;
const newStr = displayStr.length === 1 ? '0' : displayStr.slice(0, -1);
this.updateMainDisplay(newStr);
}
calculate() {
return this.operationType === 'divide' && this.num2 === 0
? false
: round(operations[this.operationType](this.num1, this.num2));
}
operation(operationType) {
// first operation, or num1 previously updated via percentage
if (this.num1 === null || this.currentNumberUpdated) {
this.operationType = operationType;
this.num1 = this.getDisplayedNumber();
// we'll display the operation that's being executed e.g: "5x"
this.displayOperation(this.num1, this.operationType);
this.currentNumberUpdated = false;
return;
}
// if user had already selected an operation, update operation, e.g: "5x" -> "5+"
if (this.operatorPressed) {
this.operationType = operationType;
this.displayOperation(this.num1, this.operationType);
return;
}
if (this.isResultDisplayed()) {
let display = this.mainDisplay.textContent;
if (display.includes('Error')) return;
this.num1 = +display.replace('= ', '');
} else {
// if user wants to chain operations, more than a pair of operands, e.g: 12+7-
// we need to execute the current operation first, before starting the new one
this.num2 = this.getDisplayedNumber();
const result = this.calculate();
// in case division by 0, result will be false
if (result === false) {
this.updateMainDisplay(`= Error`);
return;
}
// store the result in num1 before continuing to the next operation
this.num1 = result;
}
// display the new operation
this.operationType = operationType;
this.displayOperation(this.num1, this.operationType);
}
result() {
// if operation is not defined, don't do anything
if (!this.operationType) return;
// the value of num2 depends on the user previous actions:
if (this.operatorPressed) {
// if user presses "=" straight after an operation without entering a second number, num2 will be equal to the first number, e.g: 5+= 10
this.num2 = this.num1;
} else if (this.currentNumberUpdated || this.isResultDisplayed()) {
// if num1 was updated via % button or there is a result on the display, get the number and assign to num1, num2 stays the same, just update num1
//e.g: 1+2=3, display: =3, user presses result: num1 = 3, num2 = 2 (display: =5)
let display = this.mainDisplay.textContent;
if (display.includes('Error')) return;
this.num1 = +display.replace('= ', '');
} else {
// get the number on the display to be the second operand
this.num2 = +this.mainDisplay.textContent;
}
const result = this.calculate();
if (result === false) {
this.updateMainDisplay(`= Error`);
return;
}
this.displayOperation(this.num1, this.operationType, this.num2);
this.updateMainDisplay(`= ${result}`);
this.operatorPressed = false;
this.currentNumberUpdated = false;
}
}
const mainDisplay = document.querySelector('.main-display');
const operationDisplay = document.querySelector('.operation-display');
const calculator = new Calculator(mainDisplay, operationDisplay);
const handleClick = e => {
if (!e.target.closest('button')) return;
const btnTarget = e.target.closest('button').dataset.target;
if (btnTarget === 'operator') {
const operationType = e.target.closest('button').dataset.operation;
calculator.operation(operationType);
return;
}
if (btnTarget === 'operand') {
//if there's a result on the display, clear first
if (calculator.isResultDisplayed()) calculator.clear();
calculator.displayOperand(e.target.textContent);
return;
}
// execute clear, backspace, percentage or result methods
calculator[btnTarget]();
};
// Add Event Listener to the buttons container: event delegation
document.querySelector('.buttons').addEventListener('click', handleClick);
// keyboard support
window.addEventListener('keydown', function (e) {
let key = document.querySelector(`button[data-key='${e.key}']`);
if (e.key === ',') key = document.querySelector(`button[data-key='.']`);
if (key) key.click();
});