-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
325 lines (270 loc) · 7.79 KB
/
main.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
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
class CalculatorEvaluation {
constructor() {
this.operands = [];
this.operator = '';
this.divideByZeroError = false;
}
// Evaluate expression
evaluate(displayObj) {
let result;
// Person operation on available operands
// (i.e if only one operand is available, make that operand the second)
switch(this.operator) {
case 'add': result = this.add(); break;
case 'sub': result = this.sub(); break;
case 'mul': result = this.mul(); break;
case 'div': result = this.div(); break;
}
this.clear(result);
displayObj.clear();
return result;
}
// Addition helper
add() {
return this.operands[0] + (this.operands[1] || this.operands[0]);
}
// Subtraction helper
sub() {
return this.operands[0] - (this.operands[1] || this.operands[0]);
}
// Multiplication helper
mul() {
return this.operands[0] * (this.operands[1] || this.operands[0]);
}
// Division helper
// Returns undefined for division by zero
div() {
if (this.operands[1] === 0) {
return undefined;
}
return this.operands[0] / (this.operands[1] || this.operands[0]);
}
// Reset evaluation object
clear(result) {
if (result === undefined) {
this.operands = [];
this.operator = '';
}
this.divideByZeroError = false;
}
}
class CalculatorDisplay {
constructor(domObj, maxDisplayDigits) {
this.str = '0';
this.domObj = domObj;
this.maxDisplayDigits = maxDisplayDigits;
this.show();
}
// Display error message
showError(errorMsg) {
this.str = '0';
this.show(errorMsg);
}
// Display number
showNumber(num) {
this.str = String(num);
this.show();
}
// Display number input from calculator button
showNumberFromButton(numStr, previousClick) {
// Check if clicked number should be displayed as is or appended
if (previousClick.type === 'decimal' || this.str !== '0') {
if (this.canBeDisplayed(this.str + numStr)) {
this.str += numStr;
}
} else {
this.str = numStr;
}
return this;
}
// Append decimal point to display
showDecimalPoint(previousClick) {
if (previousClick.type === 'operator') {
this.clear();
}
if (!this.str.includes('.')) {
this.str += '.';
this.show();
}
return this;
}
// TODO - Disable backspace for calculation result
// Delete a single digit from display
removeCharacter() {
if (
(this.str.length === 2 && this.str.startsWith('-'))
|| this.str.length < 2
) {
this.str = '0';
} else {
this.str = this.str.slice(0, this.str.length - 1);
}
this.show();
}
// Check if a given string will fit on the display
canBeDisplayed(str) {
let strLen;
if (str.includes('.')) {
str = this.processFloat(str);
strLen = str.length - 1;
} else {
strLen = str.length;
}
return strLen <= this.maxDisplayDigits;
}
// Try and fit a floating point number on the display
processFloat(floatStr) {
const numDigits = floatStr.length - 1;
const numDigitsWholeNumber = floatStr.split('.')[0].length;
if (numDigits > this.maxDisplayDigits) {
let decimalPlaces = displayObj.maxDisplayDigits - numDigitsWholeNumber;
decimalPlaces = (decimalPlaces < 0) ? 0 : decimalPlaces;
floatStr = Number(floatStr).toFixed(decimalPlaces);
}
return floatStr;
}
// Push a string to the display
show(str) {
this.domObj.textContent = str || this.str;
}
// Clear display contents
clear() {
this.str = '0';
this.domObj.textContent = this.str;
}
}
// ---| INITIALIZATION |---
// DOM ELEMENTS
document.body.focus();
const numberDisplay = document.querySelector('.display > .number');
const numberBtns = document.querySelectorAll('button[data-type="number"]');
const operatorBtns = document.querySelectorAll('button[data-type="operator"]');
const utilityBtns = document.querySelectorAll('button[data-type="utility"]');
// CUSTOM OBJECTS
const previousClick = {type: null};
const evalObj = new CalculatorEvaluation();
const displayObj = new CalculatorDisplay(numberDisplay, 9);
// ---| EVENT LISTENERS |---
document.body.addEventListener('keydown', handleKeyDown);
numberBtns.forEach((btn) => {
btn.addEventListener('click', handleNumberClick)
});
operatorBtns.forEach((btn) => {
btn.addEventListener('click', handleOperatorClick)
});
utilityBtns.forEach((btn) => {
btn.addEventListener('click', handleUtilityClick)
});
// ---| EVENT HANDLERS |---
function handleKeyDown(e) {
e.preventDefault();
const key = e.key;
const validOperatorSymbols = ['+', '-', '*', '/', '=', 'Enter'];
if (!isNaN(key)) {
processNumberInput(key);
} else if (validOperatorSymbols.includes(key)) {
processOperatorInput(convertSymbolToOperator(key));
} else {
processUtilityInput(key);
}
}
function handleNumberClick(e) {
const clickedNumber = e.target.textContent;
processNumberInput(clickedNumber);
}
function handleOperatorClick(e) {
const clickedOperator = e.target.dataset.key;
processOperatorInput(clickedOperator);
}
function handleUtilityClick(e) {
const clickedUtility = e.target.dataset.key;
processUtilityInput(clickedUtility);
}
// ---| CALCULATOR HELPERS |---
function convertSymbolToOperator(symbol) {
switch(symbol) {
case '+': return 'add';
case '-': return 'sub';
case '*': return 'mul';
case '/': return 'div';
case '=': case 'Enter': return 'equ';
}
}
function processUtilityInput(util) {
switch(util) {
case 'cls':
displayObj.clear();
evalObj.clear();
enableButtonCollection(operatorBtns, numberBtns, utilityBtns);
break;
case 'dec': case '.':
displayObj.showDecimalPoint(previousClick);
break;
case 'bck': case 'Backspace':
displayObj.removeCharacter();
break;
}
}
function processOperatorInput(operator) {
if (previousClick.type === 'number') {
const newOperand = Number(displayObj.str);
if (evalObj.operands.length === 0) {
evalObj.operands[0] = newOperand;
} else {
evalObj.operands.push(newOperand);
}
} else if (evalObj.operands.length === 2 && operator !== 'equ') {
evalObj.operands.pop();
}
if (evalObj.operands.length === 2 || operator === 'equ') {
const result = evalObj.evaluate(displayObj);
const filteredResult = determineDisplayAction(result);
if (filteredResult) {
evalObj.operands[0] = filteredResult;
}
}
if (operator !== 'equ') {
evalObj.operator = operator;
}
previousClick.type = 'operator';
}
function processNumberInput(num) {
if (previousClick.type === 'operator') {
if (evalObj.divideByZeroError) {
disableButtonCollection(operatorBtns);
}
displayObj.clear();
}
displayObj.showNumberFromButton(num, previousClick).show();
previousClick.type = 'number';
}
function determineDisplayAction(result) {
let resultStr = String(result);
if (result === undefined) {
resultStr = 'Cannot divide by zero';
} else if (resultStr.includes('.')) {
resultStr = displayObj.processFloat(resultStr);
}
if (result !== undefined && !displayObj.canBeDisplayed(resultStr)) {
resultStr = 'Number too large';
}
if (!isNaN(resultStr)) {
displayObj.showNumber(resultStr);
return Number(resultStr);
} else {
displayObj.showError(resultStr);
disableButtonCollection(operatorBtns, numberBtns, utilityBtns);
document.querySelector('[data-key="cls"]').disabled = false;
}
return undefined;
}
function disableButtonCollection(...btnCollection) {
btnCollection.forEach((group) => {
group.forEach((btn) => btn.disabled = true);
});
}
function enableButtonCollection(...btnCollection) {
btnCollection.forEach((group) => {
group.forEach((btn) => btn.disabled = false);
});
}