-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjavascript.js
More file actions
443 lines (383 loc) · 14 KB
/
javascript.js
File metadata and controls
443 lines (383 loc) · 14 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
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
'use strict'
let number1 = {
integerPart: '0', // type: string
sign: 1,
containsDecimal: false,
decimalPart: '', // type: string
computedValue: function() {
const decimal = this.containsDecimal ? '.' : '';
return Number(this.integerPart + decimal + this.decimalPart) * this.sign;
}
};
let number2 = {
integerPart: '',
sign: 1,
containsDecimal: false,
decimalPart: '',
computedValue: function() {
const decimal = this.containsDecimal ? '.' : '';
return Number(this.integerPart + decimal + this.decimalPart) * this.sign;
}
};
let operators = {
add: {
symbol: '+',
fn: (x, y) => x + y,
},
subtract: {
symbol: '-',
fn: (x, y) => {
let difference = x - y;
let errorMargin = Number.EPSILON * Math.max(1, Math.abs(x), Math.abs(y)); // account for floating point errors, e.g. (0.1 + 0.2) - 0.3 => 5.551115123125783e-17
return Math.abs(difference) < errorMargin ? 0 : difference;
},
},
multiply: {
symbol: '×',
fn: (x, y) => x * y,
},
divide: {
symbol: '÷',
fn: (x, y) => {
if (y === 0) {
isError = true;
errorType = 'divisionByZero';
}
return x / y;
},
},
power: {
symbol: '^',
fn: (x, y) => {
if (x === 0 && y < 0) {
isError = true;
errorType = 'divisionByZero';
}
return x ** y;
},
},
};
const errorMessages = {
infinity: 'Number too big!',
divisionByZero: `Can't divide by 0`,
default: 'Error',
}
const displayLimit = 13; // max # of characters
let operatorName = null; // e.g. 'add'
let result = null;
let resultDisplayString = null;
let isError = false;
let errorType = null;
// DOM elements
const displayLineTop = document.querySelector('.line-1');
const displayLineBottom = document.querySelector('.line-2');
const buttons = document.querySelectorAll('button');
// Handle button clicks
buttons.forEach(button => {
button.addEventListener('click', (e) => {
const buttonId = e.target.id;
const buttonText = e.target.innerText;
if (isError) {
resetCalculator();
}
// Number button clicked
if (isNumber(buttonText)) {
handleNumberInput(buttonText);
return;
}
// Operator button clicked
if (operators.hasOwnProperty(buttonId)) {
handleOperatorInput(buttonId);
return;
}
// Other button clicked
switch (buttonId) {
case 'decimal':
handleDecimalInput();
break;
case 'sign-toggle':
handleSignToggleInput();
break;
case 'equal':
handleEqualInput();
break;
case 'backspace':
handleBackspaceInput();
break;
case 'clear':
resetCalculator();
updateDisplay();
break;
}
});
});
// Keyboard support
document.addEventListener('keydown', (e) => {
const keyPressed = e.key;
if (isError) {
resetCalculator();
}
if (isNumber(keyPressed)) {
handleNumberInput(keyPressed);
return;
}
switch (keyPressed) {
case '-':
if (!number1.integerPart || (operatorName && !number2.integerPart)) { // flip signs only at the start of number inputs
handleSignToggleInput();
} else {
handleOperatorInput('subtract');
}
break;
case '+':
handleOperatorInput('add');
break;
case '*':
handleOperatorInput('multiply');
break;
case '/':
handleOperatorInput('divide');
break;
case '^':
handleOperatorInput('power');
break;
case '.':
handleDecimalInput();
break;
case 'Enter':
e.preventDefault();
handleEqualInput();
break;
case 'Backspace':
handleBackspaceInput();
break;
case 'Escape':
resetCalculator();
updateDisplay();
break;
}
});
function isNumber(inputString) {
const isNumber = !Number.isNaN(parseInt(inputString));
return isNumber;
}
function handleNumberInput(numberInput) {
if (result !== null && !operatorName) resetCalculator(); // Reset calculator if number is entered on top of a result without any operations
if (displayLineBottom.innerText.length === displayLimit) return;
if (operatorName) {
if (number2.containsDecimal) {
number2.decimalPart += numberInput;
} else if (number2.integerPart === '0') {
number2.integerPart = numberInput;
} else {
number2.integerPart += numberInput;
}
} else {
if (number1.containsDecimal) {
number1.decimalPart += numberInput;
} else if (number1.integerPart === '0') {
number1.integerPart = numberInput; // NEW LINE
} else {
number1.integerPart += numberInput;
}
}
updateDisplay();
}
function handleOperatorInput(newOperatorName) {
if (!number1.integerPart) return;
if (number2.integerPart) { // calculate existing number pairs before adding the new operator symbol
calculate();
}
operatorName = newOperatorName;
updateDisplay();
}
function handleDecimalInput() {
if (result !== null && !operatorName) resetCalculator(); // Reset calculator if decimal is entered on top of a result without any operation
if (displayLineBottom.innerText.length === displayLimit) return;
// Prevent adding decimal if number is in exponential form. This would cause NaN issues.
if (operatorName && !number2.containsDecimal && !number2.integerPart.includes('e')) {
number2.containsDecimal = true;
number2.integerPart ||= '0';
} else if (!number1.containsDecimal && !number1.integerPart.includes('e') && !operatorName) {
number1.containsDecimal = true;
number1.integerPart ||= '0';
}
updateDisplay();
}
function handleSignToggleInput() {
if (operatorName) {
if (number2.sign > 0 && displayLineBottom.innerText.length > displayLimit - 3) return; // need to reserve at least 3 characters for '(-)' symbols
number2.sign *= -1;
} else {
if (number1.sign > 0 && displayLineBottom.innerText.length === displayLimit) return;
number1.sign *= -1;
}
updateDisplay();
}
function handleEqualInput() {
if (!number2.integerPart) return;
calculate();
operatorName = null;
updateDisplay();
}
function handleBackspaceInput() {
if (result !== null && !operatorName) { // Reset & clear calculator if backspace is entered on top of a result without any operation
resetCalculator();
updateDisplay();
return;
}
if (displayLineBottom.innerText === '') return;
if (number2.integerPart || number2.sign < 0) {
removeLastCharacter(number2);
} else if (operatorName) {
operatorName = null;
} else {
removeLastCharacter(number1);
}
updateDisplay();
}
function updateDisplay() {
if (isError) {
displayErrorMessage();
return;
}
const operatorSymbol = operatorName ? operators[operatorName].symbol : '';
const number1String = resultDisplayString ?? createNumberString(number1);
const number2String = (number2.sign < 0) ? `(${createNumberString(number2)})` : createNumberString(number2);
if (operatorName) {
displayLineTop.textContent = number1String + ' ' + operatorSymbol;
displayLineBottom.textContent = number2String;
} else {
displayLineTop.textContent = '';
displayLineBottom.textContent = number1String;
}
}
function displayErrorMessage() {
displayLineTop.textContent = errorMessages[errorType];
displayLineBottom.textContent = errorMessages.default;
}
function createNumberString(number) {
const sign = number.sign < 0 ? '-' : '';
const decimalPart = number.containsDecimal ? `.${number.decimalPart}`: '';
const intPart = number.integerPart;
const numberString = sign + intPart + decimalPart;
return numberString;
}
function removeLastCharacter(number) {
if (number.containsDecimal) {
if (!number.decimalPart) {
number.containsDecimal = false;
} else {
number.decimalPart = number.decimalPart.slice(0, -1);
}
return;
}
if (!number.integerPart && number.sign < 0) {
number.sign = 1;
} else if (number.integerPart.length === 1) {
number.integerPart = '';
} else {
number.integerPart = number.integerPart.slice(0, -1);
}
}
function resetCalculator() {
displayLineTop.innerText = '';
displayLineBottom.innerText = '';
resetNumber(number1);
resetNumber(number2);
operatorName = null;
result = null;
resultDisplayString = null;
isError = false;
errorType = null;
}
function resetNumber(number) {
number.integerPart = (number === number1) ? '0' : '';
number.sign = 1;
number.containsDecimal = false;
number.decimalPart = '';
}
function operate(number1, number2, operatorFn) {
return operatorFn(number1, number2);
}
function calculate() {
result = operate(number1.computedValue(), number2.computedValue(), operators[operatorName].fn);
// Tests: Show unprocessed result in console
console.log(`${number1.computedValue()} ${operators[operatorName].symbol} ${number2.computedValue()}`);
console.log('Unprocessed result is:');
console.log(result);
// Check for big number errors
if ((result === Infinity || result === -Infinity) && errorType !== 'divisionByZero') {
isError = true;
errorType = 'infinity';
return;
}
updateResultDisplayString();
updateNumber1(String(result));
resetNumber(number2);
}
function updateNumber1(resultString) {
if (resultString.includes('.')) {
const [intPart, decimalPart] = resultString.split('.');
number1.integerPart = String(Math.abs(intPart));
number1.containsDecimal = true;
number1.decimalPart = decimalPart;
} else {
number1.integerPart = String(Math.abs(result));
number1.containsDecimal = false;
number1.decimalPart = '';
}
number1.sign = result < 0 ? -1 : 1;
}
function updateResultDisplayString() {
const absResult = Math.abs(result);
const isNegative = result < 0;
const resultString = String(result);
const containsDecimal = resultString.includes('.');
const maxIntegerPlaces = displayLimit - Number(isNegative);
// standardFormLimitMax EXPLANATION:
// At or above the standardFormLimitMax, rounding into standard form would cause display overflow
// This limit is reduced by a decimal place to account for negative sign character
// The -0.5 is applied since rounding up would add an extra decimal place
const standardFormLimitMax = (10 ** maxIntegerPlaces) - 0.5;
const standardFormLimitMin = 1e-6; // numbers automatically switch to exponential notation when smaller than this
resultDisplayString = resultString;
// CASE: RESULT FITS DISPLAY AS IS
if (resultDisplayString.length <= displayLimit) return;
// CASE: STANDARD FORM FRACTIONAL NUMBERS (with up to a few leading zeros) -> round to the last decimal place that fits in the display
if (containsDecimal && (absResult < standardFormLimitMax) && (absResult >= standardFormLimitMin)) {
let integerLength = String(parseInt(absResult)).length;
let decimalPlaces = Math.max(0, maxIntegerPlaces - integerLength - 1); // -1 accounts for decimal character
resultDisplayString = String(parseFloat(result.toFixed(decimalPlaces))); // Note: parseFloat used to remove trailing zeros, which may be significant
console.log(`result display string: ${resultDisplayString}`);
console.log(`character length: ${resultDisplayString.length}`);
return;
}
// CASE: VERY SMALL NUM (small in magnitude; practically zero) -> convert to scientific notation to prevent significant digits from being pushed off display
if (absResult < standardFormLimitMin) {
let significantDigits = 15;
let fractionDigits = displayLimit - 5; // -5 to account for the integer (1), decimal (1), and 'e-n' (3) characters when converting to exponential
if (isNegative) fractionDigits--; // account for negative sign
if (absResult < 1e-9) fractionDigits--; // +1 character in exponent -> 'e-nn'
if (absResult <= 1e-100) fractionDigits-- ; // +1 character in exponent -> 'e-nnn'
// Limit significant digits to avoid showing potential floating point errors. Converting back to number removes trailing zeros.
// e.g. 1 / 10 / 10 => 1.0000000000000002e-7 -> '1.00000000000000e-7' -> 1e-7
resultDisplayString = shortenedExponential(Number(result.toPrecision(significantDigits)), fractionDigits);
return;
}
// CASE: BIG NUM
if (absResult >= standardFormLimitMax) {
let fractionDigits = displayLimit - 6; // -6 to account for the integer (1), decimal (1), and 'e-nn' (4) characters when converting to exponential
if (isNegative) fractionDigits--; // account for negative sign
if (absResult >= 1e+99 ) fractionDigits--; // account for +1 exponent digit ('e-nnn')
resultDisplayString = shortenedExponential(result, fractionDigits);
return;
}
// Tests
console.log('⚠️ WARNING: result not handled!');
}
function shortenedExponential(number, fractionDigits) {
const defaultExponential = number.toExponential(); // not specifying the fraction digits leads excludes trailing 0's
const maxExponential = number.toExponential(fractionDigits);
return defaultExponential.length <= maxExponential.length ? defaultExponential : maxExponential;
}