-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
1101 lines (468 loc) · 21.6 KB
/
app.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// BUDGET CONTROLLER MODULE
var budgetController = (function(){
// Private Functions
var Expense = function(id, description, value){
this.id = id; // Function Constructor
this.description = description;
this.value = value;
this.percentage = -1;
};
// This method will calculate the Percentage
Expense.prototype.calcPercentage = function(totalIncome){
if (totalIncome > 0){
this.percentage = Math.round((this.value/totalIncome)*100);
}
else{
this.percentage = -1;
}
};
// This method will return the percentage
Expense.prototype.getPercentage = function(){
return this.percentage;
};
// Private Functions
var Income = function(id, description, value){
this.id = id; // Function Constructor
this.description = description;
this.value = value;
};
var calculateTotal = function(type){
var sum = 0;
data.allItems[type].forEach(function(cur){
sum += cur.value;
});
data.totals[type] = sum;
/*
sum = 0
[200, 400, 600]
sum = 0 + 200
sum = 200
sum = 200 + 400
sum = 600
sum = 600 + 600
sum = 1200
*/
}
// Creating a strong data structure to store all of Income, expenses, total, etc...
// data object
var data = {
allItems: { // allItems is also an object
inc: [], // array which will store all instances of incomes
exp: [] // array which will store all instances of expenses
},
totals: { // totals is an object
inc : 0, // Total Incomes
exp : 0 // Total expenses
},
budget : 0,
percentage : -1 //Non existent
};
// Add New Item Public Method
return {
addItem: function(type, des, val){
var newItem, ID;
// Create new ID: ID = lastID + 1
if(data.allItems[type].length > 0){
ID = data.allItems[type][data.allItems[type].length-1].id+1;
}
else{
ID = 0;
}
// Create new Item based on 'exp' or 'inc'
if (type === 'exp'){
newItem = new Expense(ID, des, val); // Create an Expense object
}
else if (type === 'inc'){
newItem = new Income(ID, des, val); // Create an Income object
}
/*
1. No need of if - else statements to determine the <type> as <'exp'> or <'inc'>.
For example:
1. Let's consider the type as 'exp'.
2. So, from the data object...
a) 'allItems' object will be selected.
b) 'exp' array will be selected.
3. Now the 'push' method will be used which will add the 'newItem' at the end of the array of the 'exp'.
*/
// Push into our data Structure
data.allItems[type].push(newItem);
// Finally return our new Item
return newItem;
},
// Deleting Item from Budget Controller
deleteItem: function(type, id){
var ids, index;
/*
Array Map() method:
array.map(function(currentValue, index, arr), thisValue)
Map returns the result in the form of an array
*/
ids = data.allItems[type].map(function(current){
return current.id;
});
index = ids.indexOf(id);
/*
Array Splice() method:
array.splice(index, howmany, item1, ....., itemX)
*/
if(index!== -1){
data.allItems[type].splice(index, 1);
}
},
calculateBudget: function(){
// Calculate total income and the expenses
calculateTotal('inc');
calculateTotal('exp');
// Calculate the budget: income - expenses
data.budget = data.totals.inc - data.totals.exp;
// Calculate the percentage of income that we spent
if(data.totals.inc > 0){
data.percentage = Math.round((data.totals.exp / data.totals.inc)*100);
}
else {
data.percentage = -1;
}
/*
exp = 100
inc = 200
per = (100 / 200) * 100
*/
},
// Calculate the expense percentage for each of the expense objects that are stored in the expenses array
// So for looping we use the forEach function
calculatePercentages: function(){
data.allItems.exp.forEach(function(cur){
// Each element will call the calcPercentage() method
cur.calcPercentage(data.totals.inc); // calcPercentage() calls the Expense.prototype.calcPercentage
// data.totals.inc is the Total Income Parameter
});
},
// Loop over all of our expenses
// Call the getPercentages() methodon each of our objects
getPercentage: function(){
/* The reason of using map:
1. We have to loop over the array and do something
2. [Imp] We also want to return something, we want to store somewhere
// Difference between map and forEach
3. map returns something, and stores in a variable, while forEach doesn't
*/
var allPerc = data.allItems.exp.map(function(cur){
return cur.getPercentage(); // We call the result of the getPercentage() method from Expense.prototype.getPercentage
// Return the percentage of a particular object in the exp array and store it in allPerc
/*
Ex: We have 5 object in exp array;
1. So, return cur.getPercentage() will get called 5 times, for each of the 5 elements
2. So for each of them we will call the getPercentage mathod
3. Return it and store it in the allPerc array
4. Return the allPerc array
*/
});
return allPerc; // It's an array of all of the percentages
},
getBudget: function(){
//budget, total inc, total exp, percentage
return{
budget: data.budget,
totalInc : data.totals.inc,
totalExp : data.totals.exp,
percentage : data.percentage
}
},
testing: function(){
console.log(data);
}
};
})();
// UI CONTROLLER MODULE
var UIController = (function(){
// Private Method syntax (no return)
// Eache element inside this DOM Tree is called a node
var DOMStrings = {
inputType: '.add__type',
inputDescription: '.add__description',
inputValue: '.add__value',
inputBtn: '.add__btn',
incomeContainer: '.income__list',
expensesContainer: '.expenses__list',
budgetLabel: '.budget__value',
incomeLabel: '.budget__income--value',
expenseLabel: '.budget__expenses--value',
percentageLabel: '.budget__expenses--percentage',
container: '.container',
expensePercLabel: '.item__percentage',
dateLabel: '.budget__title--month'
};
var formatNumber = function(num, type){
var numSplit, int, dec, type, sign;
/*
1. + or - before the number
2. exactly 2 decimal points (rounded off)
3. comma sepreator for the thousands
Example:
2310.4567 -> + 2,310.46
2000 -> + 2000.00
*/
num = Math.abs(num); // Absolute number, Overiding the num argument
num = num.toFixed(2);
/*
1. Till 2 decimal points
2. Returns a string (rounded off automatically)
3. (i) 2.4567.toFixed(2) => "2.46"
(ii) 2.toFixed(2) => "2.00"
*/
// Updated the 'num' to Strings Ex: 2.3456 as "2.35"
numSplit = num.split('.');
int = numSplit[0];
if(int.length > 3){
/*
string.substr(start, length)
1. start: The position where to start the extraction.
2. length: The number of characters to extract
*/
// int = int.substr(0, 1) + ',' + int.substr(1, 3); //2310 => 2,310 (hard coded)
int = int.substr(0, int.length-3) + ',' + int.substr(int.length - 3, 3); //Dynamic
}
dec = numSplit[1];
// type = 'exp' ? sign = '-' : sign = '+';
return (type === 'exp' ? '-' : '+') + ' ' + int + '.' + dec ;
};
var nodeListForEach = function(list, callback){ // list refers to the nodeList (expensePercLabel)
for (var i = 0; i < list.length; i++){ // For loop: In each iteration will call the callback Function
callback(list[i], i); // current => list at position i; index => i
}
};
// Public method syntax: Return an object from the function i.e., the module
return{
// We return an object
getInput: function(){ //getInput is an object
return{
type: document.querySelector(DOMStrings.inputType).value,
description: document.querySelector(DOMStrings.inputDescription).value,
value: parseFloat(document.querySelector(DOMStrings.inputValue).value) // String to Float
};
},
// Add new item to the UI
addListItem: function(obj, type){
var html, newHtml, element;
// Create HTML string with the placeholder text
if (type === 'inc'){
// Income
element = DOMStrings.incomeContainer;
html = '<div class="item clearfix" id="inc-%id%"> <div class="item__description">%description%</div> <div class="right clearfix"> <div class="item__value">%value%</div> <div class="item__delete"> <button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button> </div> </div> </div>';
}
else if (type === 'exp'){
// Expense
element = DOMStrings.expensesContainer;
html = '<div class="item clearfix" id="exp-%id%"> <div class="item__description">%description%</div> <div class="right clearfix"> <div class="item__value">%value%</div> <div class="item__percentage">21%</div> <div class="item__delete"> <button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button> </div> </div> </div>';
}
// Replace the placeholder text with some actual data
newHtml = html.replace('%id%', obj.id);
newHtml = newHtml.replace('%description%', obj.description);
newHtml = newHtml.replace('%value%', formatNumber(obj.value, type));
// Insert the HTML into the DOM
document.querySelector(element).insertAdjacentHTML('beforeend', newHtml);
},
deleteListItem: function(selectorID){
/*
node.removeChild(node)
*/
var el = document.getElementById(selectorID);
el.parentNode.removeChild(el);
},
// To clear the input fields after each entry
clearFields: function(){
var fields, fieldsArr;
fields = document.querySelectorAll(DOMStrings.inputDescription + ', ' + DOMStrings.inputValue);
/*
1. querySelectorAll returns a LIST
2. We need to convert into an array.
3. array method -> .slice()
4. To return the copy of the array that it's called on.
5. But we cannot implement using:
fields.slice();
6. Instead we use the syntax given below.
*/
fieldsArr = Array.prototype.slice.call(fields);
/*
1. Syntax forEach:
arr.forEach(callback(currentValue [, index [, array]])[, thisArg])
2. callback:
Function to execute on each element
3. currentValue:
The current element being processed in the array
4. index: [OPTIONAL]
The index of the currentValue in the array
5. array: [OPTIONAL]
The array forEach was called upon.
*/
fieldsArr.forEach(function(current, index, array){
current.value = "";
});
fieldsArr[0].focus();
},
displayBudget: function(obj){
var type;
obj.budget > 0 ? type = 'inc' : type = 'exp';
document.querySelector(DOMStrings.budgetLabel).textContent = formatNumber(obj.budget, type);
document.querySelector(DOMStrings.incomeLabel).textContent = formatNumber(obj.totalInc, 'inc');
document.querySelector(DOMStrings.expenseLabel).textContent = formatNumber(obj.totalExp, 'exp');
if(obj.percentage > 0){
document.querySelector(DOMStrings.percentageLabel).textContent = obj.percentage + '%';
}
else{
document.querySelector(DOMStrings.percentageLabel).textContent = '---';
}
},
// Method to display the percentages of expenses besides the respective expenses
displayPercentages: function(percentages){
/*
Reason we used the querySelectorAll():
1. We have to select all the elements which have the 'item__percentage' class
2. We don't know how many expense item would be on the list.
3. We cannot use the querySelector() because that only selects the first one.
4. So we need to use the querySelectorAll().
*/
var fields = document.querySelectorAll(DOMStrings.expensePercLabel); // This will return a node List
/*
1. We need to loop over all of these elements in our querySelectorAll() / Nodes that contains the item__percentage class.
2. Then we need to change the textContent property for all of them.
Lists / NodeList does NOT have the property '.forEach'
But... Lists / NodeList have '.length' property
*/
//array.forEach(function(currentValue, index, arr), thisValue)
// Call the function
nodeListForEach(fields, function(current, index){ // function(current, index) => callback(list[i], i)
if (percentages[index] > 0){
current.textContent = percentages[index] + '%'; // current -> document.querySelectorAll(DOMStrings.expensePercLabel)
}
else {
current.textContent = '---';
}
});
},
// Method for displaying the current month
displayMonth: function(){
var now, year, month, monthArr;
now = new Date();
//var christmas = new Date(2020, 12, 25);
monthArr = ['January', ' Feburary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
month = now.getMonth(); // Return the current month (For Example: 6)
// getFullYear is a method, so we have to call it by getFullYear()
year = now.getFullYear(); // Return the current year (For Example: 2020)
// monthArr[month] => monthArr[6] => June
document.querySelector(DOMStrings.dateLabel).textContent = monthArr[month] + ' ' + year;
},
changedType: function(){
var fields = document.querySelectorAll(
DOMStrings.inputType + ',' +
DOMStrings.inputDescription + ',' +
DOMStrings.inputValue
);
nodeListForEach(fields, function(cur){
cur.classList.toggle('red-focus');
});
document.querySelector(DOMStrings.inputBtn).classList.toggle('red');
},
// Exposing the private DOMStrings method to public to be accessed by another module
getDOMStrings: function(){
return DOMStrings;
}
};
})();
// GLOBAL APP CONTROLLER MODULE
var controller = (function(budgetCtrl, UICtrl){
var setUpEventListeners = function(){
// Accessing the Private DOMStrings method from the UI controller which was exposed
var DOM = UICtrl.getDOMStrings();
//ctrlAddItem is the callback function
document.querySelector(DOM.inputBtn).addEventListener('click', ctrlAddItem);
// If the user wants to press enter and continue rather than clicking on the tick mark button
document.addEventListener('keypress', function(event){
//console.log(event);
if (event.keyCode === 13 || event.which === 13){
ctrlAddItem();
}
});
//ctrlDeleteItem is the callback function
document.querySelector(DOM.container).addEventListener('click', ctrlDeleteItem);
//changedType is the callback function
document.querySelector(DOM.inputType).addEventListener('change', UICtrl.changedType);
};
// Called each time we enter a new item in the user Interface
var updateBudget = function(){
// 1. Calculate the budget
budgetCtrl.calculateBudget();
// 2. Method to Return the budget
/*
var1 <- method that returns budget
*/
var budget = budgetCtrl.getBudget();
// 3. Display the budget on the user interface
/*
Display : Pass on var1
*/
UICtrl.displayBudget(budget);
};
var updatePercentages= function(){
// Calculate the percentages
budgetCtrl.calculatePercentages();
// Read the percentages from the Budget Controller
var percentages = budgetCtrl.getPercentage();
// Update the new Percentages in the UI
UICtrl.displayPercentages(percentages);
};
// Add Item
var ctrlAddItem = function(){
var input, newItem;
// 1. Get the field input Data
input = UICtrl.getInput();
if (input.description !== "" && !isNaN(input.value) && input.value > 0){
// 2. Add the item to the budget controller
newItem = budgetCtrl.addItem(input.type, input.description, input.value);
// 3. Add the item to the UI Controller
UICtrl.addListItem(newItem, input.type);
// 4. Clear the fields
UICtrl.clearFields();