-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.js
468 lines (339 loc) · 16.5 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
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
/*
For instructions or to run please see README.md or go to https://github.com/EncompassingResidential/John-Calculator.git
*/
let calculatorHistoryItem = {
calculation: "",
result: null
}
let initialStateItems = {
entryInputLeftOperand: "",
entryInputRightOperand: "",
entryCurrentOperator: "", // will be single character string '+', '-', '*', '/', '%'
entryFieldIsMultiDigitNumber: false,
operationNumberSum: 0,
operationIsContinousFunction: false,
operationRunningHistory: "",
calculatorHistory: [calculatorHistoryItem],
addCommaBeforePeriod: null
};
function addCommaBeforePeriod(floatNumber) {
let str = floatNumber.toString().split(".");
str[0] = str[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return str.join(".");
}
let calculatorStateItems = initialStateItems;
initializeCalculator();
function getDateString() {
const daylist = ["Sunday","Monday","Tuesday","Wednesday ","Thursday","Friday","Saturday"];
const today = new Date();
const dayOfWeek = today.getDay();
let date = (today.getMonth().toString().padStart(1, '0') + 1) +
'-' + (today.getDate() < 10 ? "0" + today.getDate() : today.getDate()) +
'-' + today.getFullYear();
return daylist[dayOfWeek] + " " + date;
}
function getTimeString() {
let today = new Date();
return today.getHours() + ":" + (today.getMinutes() < 10 ? "0" : "") + today.getMinutes() + ":" + (today.getSeconds() < 10 ? "0" : "") + today.getSeconds();
}
function initializeCalculator() {
getCalculatorStateFromLocalStorage();
initalizeInputForm();
let fieldEntryResult = document.getElementById("field-entry-result");
// Web Dev Simplified stated that innerHTML is easily hacked, so use textContent
fieldEntryResult.textContent = addCommaBeforePeriod( calculatorStateItems.operationNumberSum );
let fieldCalculatorHistory = document.getElementById("field-calculator-history");
if (calculatorStateItems.calculatorHistory.length >= 1 && calculatorStateItems.calculatorHistory[0].result !== null){
fieldCalculatorHistory.textContent += '\r\n\r\n';
calculatorStateItems.calculatorHistory.forEach(element => {
fieldCalculatorHistory.textContent += element.calculation + ' = ' + element.result + `\r\n`;
});
}
writeCalculatorStateToLocalStorage();
}
function initalizeInputForm() {
document.getElementById('field-entry-result').addEventListener('click', (e) => {
e.preventDefault();
resultFieldClicked();
});
document.getElementById('button-clear-reset').addEventListener('click', (e) => {
e.preventDefault();
clearButtonClicked();
});
document.getElementById('button-equal').addEventListener('click', (e) => {
e.preventDefault();
calculateRunningSum();
calculateFinalSum();
});
document.getElementById('button-divide').addEventListener('click', (e) => {
e.preventDefault();
operatorButtonClickedForTwoOperands('/');
});
document.getElementById('button-minus').addEventListener('click', (e) => {
e.preventDefault();
operatorButtonClickedForTwoOperands('-');
});
document.getElementById('button-multiply').addEventListener('click', (e) => {
e.preventDefault();
operatorButtonClickedForTwoOperands('*');
});
document.getElementById('button-percent').addEventListener('click', (e) => {
e.preventDefault();
operatorButtonClickedForOneOperand('%');
});
document.getElementById('button-plus').addEventListener('click', (e) => {
e.preventDefault();
operatorButtonClickedForTwoOperands('+');
});
document.getElementById('button-plus-minus').addEventListener('click', (e) => {
e.preventDefault();
plusMinusButtonClicked();
});
document.getElementById('button-1').addEventListener('click', (e) => {
e.preventDefault();
numberButtonClickedAction(1);
});
document.getElementById('button-2').addEventListener('click', (e) => {
e.preventDefault();
numberButtonClickedAction(2);
});
document.getElementById('button-3').addEventListener('click', (e) => {
e.preventDefault();
numberButtonClickedAction(3);
});
document.getElementById('button-4').addEventListener('click', (e) => {
e.preventDefault();
numberButtonClickedAction(4);
});
document.getElementById('button-5').addEventListener('click', (e) => {
e.preventDefault();
numberButtonClickedAction(5);
});
document.getElementById('button-6').addEventListener('click', (e) => {
e.preventDefault();
numberButtonClickedAction(6);
});
document.getElementById('button-7').addEventListener('click', (e) => {
e.preventDefault();
numberButtonClickedAction(7);
});
document.getElementById('button-8').addEventListener('click', (e) => {
e.preventDefault();
numberButtonClickedAction(8);
});
document.getElementById('button-9').addEventListener('click', (e) => {
e.preventDefault();
numberButtonClickedAction(9);
});
document.getElementById('button-0').addEventListener('click', (e) => {
e.preventDefault();
numberButtonClickedAction(0);
});
document.getElementById('button-period').addEventListener('click', (e) => {
e.preventDefault();
periodButtonClicked();
});
} // function initalizeInputForm
function calculateRunningSum() {
let fieldEntryResult = document.getElementById("field-entry-result");
let currentOperation = '';
let currentSum = 0;
let currentLeftOperand = calculatorStateItems.entryInputLeftOperand;
let currentRightOperand = calculatorStateItems.entryInputRightOperand;
currentLeftOperand = (currentLeftOperand.search(".") !== -1) ? +(currentLeftOperand) : parseInt(currentLeftOperand);
currentRightOperand = (currentRightOperand.search(".") !== -1) ? +(currentRightOperand) : parseInt(currentRightOperand);
switch (calculatorStateItems.entryCurrentOperator) {
case '+':
currentSum = currentLeftOperand + currentRightOperand;
currentOperation = (calculatorStateItems.operationRunningHistory === "") ?
addCommaBeforePeriod(currentLeftOperand) + ' + ' +
addCommaBeforePeriod(currentRightOperand)
:
' + ' + addCommaBeforePeriod(currentRightOperand);
break;
case '-':
currentSum = currentLeftOperand - currentRightOperand;
currentOperation = (calculatorStateItems.operationRunningHistory === "") ?
addCommaBeforePeriod(currentLeftOperand) + ' - ' +
addCommaBeforePeriod(currentRightOperand)
:
' - ' + addCommaBeforePeriod(currentRightOperand);
break;
case '*':
currentSum = currentLeftOperand * currentRightOperand;
currentOperation = (calculatorStateItems.operationRunningHistory === "") ?
addCommaBeforePeriod(currentLeftOperand) + ' * ' +
addCommaBeforePeriod(currentRightOperand)
:
' * ' + addCommaBeforePeriod(currentRightOperand);
break;
case '/':
currentSum = currentLeftOperand / currentRightOperand;
currentOperation = (calculatorStateItems.operationRunningHistory === "") ?
addCommaBeforePeriod(currentLeftOperand) + ' / ' +
addCommaBeforePeriod(currentRightOperand)
:
' / ' + addCommaBeforePeriod(currentRightOperand);
break;
case '%':
currentSum = currentRightOperand / 100;
currentOperation = addCommaBeforePeriod(currentRightOperand) + ' %';
break;
default:
fieldEntryResult.textContent = "Unknown math Operator";
break;
}
calculatorStateItems.operationNumberSum = currentSum;
fieldEntryResult.textContent = addCommaBeforePeriod( calculatorStateItems.operationNumberSum );
/*
Left Operand 11 + Right Operand 22
currentOperation = currentLeftOperand + ' * ' + currentRightOperand;
currentOperation = 11 + 22
calculatorStateItems.operationNumberSum = 33
calculatorStateItems.operationRunningHistory = 11 + 22
Actor pressed - then a 47
next time here
currentOperation = 33 + 47
calculatorStateItems.operationNumberSum = 80
Then calculatorStateItems.operationRunningHistory will be 11 + 22 33 + 47
*/
calculatorStateItems.operationRunningHistory += currentOperation;
} // function calculateRunningSum
function calculateFinalSum() {
let fieldCalculatorHistory = document.getElementById("field-calculator-history");
// I know you hate comments, I thought I should say because I decided to have a blank Object
// in my Initial calculatorStateItems.calculatorHistory then this pop() was necessary.
if (calculatorStateItems.calculatorHistory.length === 1 && calculatorStateItems.calculatorHistory[0].result === null) {
calculatorStateItems.calculatorHistory.pop();
}
// BIG LESSON: forgetting how global Object used as multiple items of an array. I had assumed it created a new Object for each array instance.
let currentCalculatorHistoryItem = {
result : addCommaBeforePeriod( calculatorStateItems.operationNumberSum ),
calculation : calculatorStateItems.operationRunningHistory
}
calculatorStateItems.calculatorHistory.push(currentCalculatorHistoryItem);
fieldCalculatorHistory.textContent = 'Calculator History\r\n\r\n';
calculatorStateItems.calculatorHistory.forEach(element => {
fieldCalculatorHistory.textContent += element.calculation + ' = ' + element.result + `\r\n`;
});
calculatorStateItems.entryInputLeftOperand = "";
calculatorStateItems.entryInputRightOperand = "";
calculatorStateItems.entryCurrentOperator = "";
calculatorStateItems.entryFieldIsMultiDigitNumber = false;
calculatorStateItems.operationIsContinousFunction = false;
calculatorStateItems.operationRunningHistory = "";
// don't clear property calculatorStateItems.operationNumberSum or .calculatorHistory
writeCalculatorStateToLocalStorage();
} // function calculateFinalSum
function numberButtonClickedAction(buttonNumber) {
let fieldEntryResult = document.getElementById("field-entry-result");
if (calculatorStateItems.entryFieldIsMultiDigitNumber === true) {
calculatorStateItems.entryInputRightOperand = (calculatorStateItems.entryInputRightOperand === "0") ? buttonNumber.toString() : calculatorStateItems.entryInputRightOperand + buttonNumber.toString();
fieldEntryResult.textContent = addCommaBeforePeriod(calculatorStateItems.entryInputRightOperand);
}
else {
calculatorStateItems.entryFieldIsMultiDigitNumber = true;
fieldEntryResult.textContent = buttonNumber.toString();
calculatorStateItems.entryInputRightOperand = buttonNumber.toString();
}
writeCalculatorStateToLocalStorage();
} // function numberButtonClickedAction
function operatorButtonClickedForTwoOperands(currentOperator) {
let fieldEntryResult = document.getElementById("field-entry-result");
if (calculatorStateItems.entryInputRightOperand != "") {
// The actor is doing a multiple operator & operand math operation
if (calculatorStateItems.entryInputLeftOperand != "") {
calculatorStateItems.operationIsContinousFunction = true;
// This sums the 1st two Operands / numbers that the Actor typed in with the "previous" Operation.
calculateRunningSum();
/*
For a multiple number operation {entryFieldIsMultiDigitNumber} this sets the Operator for the next Operand.
i.e. The Actor just pressed an Operator button which is
currently acting like an Equal sign on the 2 Operands just typed in.
*/
calculatorStateItems.entryInputLeftOperand = calculatorStateItems.operationNumberSum.toString();
calculatorStateItems.entryCurrentOperator = currentOperator;
fieldEntryResult.textContent = addCommaBeforePeriod( calculatorStateItems.operationNumberSum ) + ' ' + currentOperator;
}
else {
calculatorStateItems.entryInputLeftOperand = calculatorStateItems.entryInputRightOperand;
calculatorStateItems.entryCurrentOperator = currentOperator;
fieldEntryResult.textContent = addCommaBeforePeriod( calculatorStateItems.entryInputLeftOperand ) + ' ' + currentOperator;
}
}
else {
console.log(`- calculatorStateItems.entryInputRightOperand == ""`);
}
calculatorStateItems.entryInputRightOperand = "";
calculatorStateItems.entryFieldIsMultiDigitNumber = false;
writeCalculatorStateToLocalStorage();
} // function operatorButtonClickedForTwoOperands
function operatorButtonClickedForOneOperand(currentOperation) {
let fieldEntryResult = document.getElementById("field-entry-result");
// YAGNI - future switch statement for multiple single operators
if (calculatorStateItems.entryInputRightOperand !== "") {
// This is stating that if Actor had pressed a [Number A] Operation [Number B] %
// then the 1st [Number A] Operation is canceled
// and [Number B] is acted upon as a Percent in this case
calculatorStateItems.entryInputLeftOperand = "";
calculatorStateItems.entryCurrentOperator = currentOperation;
fieldEntryResult.textContent = addCommaBeforePeriod( calculatorStateItems.entryInputRightOperand ) + ' ' + currentOperation;
calculateRunningSum();
calculateFinalSum();
writeCalculatorStateToLocalStorage();
}
} // function operatorButtonClickedForOneOperand
function clearButtonClicked() {
let fieldEntryResult = document.getElementById("field-entry-result");
fieldEntryResult.textContent = 0;
calculatorStateItems.entryInputLeftOperand = "";
calculatorStateItems.entryInputRightOperand = "";
calculatorStateItems.entryCurrentOperator = "";
calculatorStateItems.operationNumberSum = 0;
calculatorStateItems.entryFieldIsMultiDigitNumber = false;
writeCalculatorStateToLocalStorage();
}
function periodButtonClicked() {
let fieldEntryResult = document.getElementById("field-entry-result");
if ( calculatorStateItems.entryInputRightOperand.search(/\./) === -1 ) {
calculatorStateItems.entryInputRightOperand =
(calculatorStateItems.entryInputRightOperand != "" )
?
calculatorStateItems.entryInputRightOperand + "." :
"0.";
fieldEntryResult.textContent = addCommaBeforePeriod( calculatorStateItems.entryInputRightOperand );
calculatorStateItems.entryFieldIsMultiDigitNumber = true;
writeCalculatorStateToLocalStorage();
}
}
function plusMinusButtonClicked() {
let fieldEntryResult = document.getElementById("field-entry-result");
if (calculatorStateItems.entryInputRightOperand.search("-") === -1) {
calculatorStateItems.entryInputRightOperand =
(calculatorStateItems.entryInputRightOperand != "") ?
"-" + calculatorStateItems.entryInputRightOperand :
"-";
}
else {
calculatorStateItems.entryInputRightOperand =
calculatorStateItems.entryInputRightOperand.split("-")[1];
}
fieldEntryResult.textContent = addCommaBeforePeriod( calculatorStateItems.entryInputRightOperand );
calculatorStateItems.entryFieldIsMultiDigitNumber = true;
writeCalculatorStateToLocalStorage();
}
function resultFieldClicked() {
// YAGNI
}
function clearLocalStorage() {
localStorage.clear();
calculatorStateItems = initialStateItems;
}
function getCalculatorStateFromLocalStorage() {
calculatorStateLocalStorage = JSON.parse(localStorage.getItem('calculatorStateLocalStorage')) || initialStateItems;
(calculatorStateLocalStorage !== null) ? calculatorStateItems = calculatorStateLocalStorage :
console.log('<<< calculatorStateLocalStorage is null ' + getTimeString());
}
function writeCalculatorStateToLocalStorage() {
localStorage.setItem('calculatorStateLocalStorage', JSON.stringify(calculatorStateItems));
}