-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
487 lines (375 loc) · 13.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
//BUDGET MODULE
var budgetCtrl = (function()
{
var Expense = function(id, description, value)
{
this.id = id;
this.description = description;
this.value = value;
this.percentage = -1;
};
Expense.prototype.calcPercentage = function(totalIncome)
{
if(totalIncome > 0)
{
this.percentage = Math.round((this.value / totalIncome) * 100);
}
else
{
this.percentage = -1;
}
}
Expense.prototype.getPercentage = function()
{
return this.percentage;
}
var Income = function(id, description, value)
{
this.id = id;
this.description = description;
this.value = value;
};
var calculateTotal = function(type)
{
var sum = 0;
data.allItems[type].forEach(function(current, index, array)
{
sum += current.value;
});
data.totals[type] = sum;
};
var data =
{
allItems: {
exp: [],
inc: []
},
totals: {
exp: 0,
inc: 0
},
bugdet: 0,
percentage: 0,
};
return {
addItem: function(type, desc, value)
{
var newItem, ID;
//..Create the new Id
//[1, 2, 4, 6, 8], next ID = last ID + 1 = 9
if(data.allItems[type].length > 0)
{
ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
}
else
{
ID = 0;
}
if(type === 'inc')
{
newItem = new Income(ID, desc, value);
}
else if(type === 'exp')
{
newItem= new Expense(ID, desc, value);
}
data.allItems[type].push(newItem);
//..return the new item(expense or income)
return newItem;
},
deleteItem: function(type, Id)
{
var ids_Array, index;
//ids_Array = [1, 2, 4, 6, 8]
ids_Array = data.allItems[type].map(function(currentItem)
{
return currentItem.id;
});
index = ids_Array.indexOf(Id); //index of item to delete
if(index !== -1)
{
data.allItems[type].splice(index, 1);
}
},
calculateBudget: function()
{
//..Calculate total income and total expense
calculateTotal('exp');
calculateTotal('inc');
//..Calculate the budget: income - expenses
data.bugdet = 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 = 0;
}
},
calculatePercentages: function()
{
var totalIncome = data.totals.inc;
data.allItems['exp'].forEach(function(currentItem)
{
currentItem.calcPercentage(totalIncome);
});
},
getPercentages: function()
{
var allPercentages = data.allItems['exp'].map(function(currentItem)
{
return currentItem.getPercentage();
});
return allPercentages;
},
getBudget: function()
{
return {
budget: data.bugdet,
totalInc: data.totals.inc,
totalExp: data.totals.exp,
percentage: data.percentage,
}
},
};
})();
//UI CONTROLLER
var viewCtr = (function()
{
var domStrings =
{
inputType: '.add__type',
inputDescription: '.add__description',
inputAmount: '.add__value',
inputBtn: '.add__btn',
incomesContainer: '.income__list',
expensesContainer: '.expenses__list',
bugdetValue: '.budget__value',
bugdetIncomes: '.budget__income--value',
budgetExpenses: '.budget__expenses--value',
budgetExpensesPercentage: '.budget__expenses--percentage',
container: '.container',
expensesPercentages: '.item__percentage',
dateLabel: '.budget__title--month',
};
var formatNumber = function(num, type)
{
var numSplit, realPart, decimalPart;
/*
- or + before number for inc and exp respectively
2 decimal points, comma separating the thousands
2310.4567 -> 2,310.46
*/
num = Math.abs(num);
num = num.toFixed(2); //2 decimal points
numSplit = num.split('.');
realPart = numSplit[0];
if(realPart.length > 3)
{
realPart = realPart.substr(0, realPart.length - 3) + ',' + realPart.substr(realPart.length - 3, 3); //23105 -> 23,105
}
decimalPart = numSplit[1]
return (type === 'exp' ? '-' : '+') + ' ' + realPart + '.' + decimalPart;
};
return {
getInputs: function()
{
return {
type : document.querySelector(domStrings.inputType).value,
description : document.querySelector(domStrings.inputDescription).value,
amount : parseFloat(document.querySelector(domStrings.inputAmount).value)
};
},
addListItem: function(obj, type)
{
//..Create HTML string with placeholder text
var html, newHtml, element;
if(type === 'inc')
{
element = domStrings.incomesContainer;
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')
{
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)
{
var domElement = document.getElementById(selectorId);
domElement.parentNode.removeChild(domElement);
},
clearFields: function()
{
var fields, fieldsArr;
fields = document.querySelectorAll(domStrings.inputDescription + ', ' + domStrings.inputAmount);
fieldsArr = Array.prototype.slice.call(fields);
fieldsArr.forEach(function(currentElement, index, array)
{
currentElement.value = "";
});
fieldsArr[0].focus();
},
displayPercentages: function(percentages)
{
var fields = document.querySelectorAll(domStrings.expensesPercentages);
var nodeListForEach = function(list, callback)
{
for(var i = 0; i < list.length; i++)
{
callback(list[i], i);
}
};
nodeListForEach(fields, function(current, index)
{
if(percentages[index] > 0)
{
current.textContent = percentages[index] + '%';
}
else
{
current.textContent = '---';
}
});
/* OR
fieldsArray = Array.prototype.slice.call(fields);
fieldsArray.forEach(function(current, index, array)
{
if(percentages[index] > 0)
{
current.textContent = percentages[index] + '%';
}
else
{
current.textContent = '---';
}
});*/
},
displayMonth: function()
{
var now, month, year, months
now = new Date();
year = now.getFullYear();
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
month = months[now.getMonth()];
document.querySelector(domStrings.dateLabel).textContent = month + ', ' + year;
},
getDomStrings: function()
{
return domStrings;
},
displayBudget: function(obj)
{
var type;
obj.budget > 0 ? type = 'inc' : type = 'exp';
document.querySelector(domStrings.bugdetValue).textContent = formatNumber(obj.budget, type) + '$';
document.querySelector(domStrings.bugdetIncomes).textContent = formatNumber(obj.totalInc, 'inc') + '$';
document.querySelector(domStrings.budgetExpenses).textContent = formatNumber(obj.totalExp,'exp') + '$';
if(obj.percentage > 0)
{
document.querySelector(domStrings.budgetExpensesPercentage).textContent = obj.percentage + '%';
}
else
{
document.querySelector(domStrings.budgetExpensesPercentage).textContent = '--';
}
},
}
})();
//CONTROLLER MODULE
var appCtr = (function(budgetCtrl, UICtrl)
{
var setupEventListeners = function()
{
var DOM = UICtrl.getDomStrings();
document.querySelector(DOM.inputBtn).addEventListener('click', ctrlAddItem);
document.addEventListener('keypress', function(event)
{
if(event.keyCode === 13 || event.which === 13)
{
ctrlAddItem();
}
});
document.querySelector(DOM.container).addEventListener('click', ctrlDeleteItem);
};
var updateBudget = function()
{
//1. Calculate the budget
budgetCtrl.calculateBudget();
//2. Return the budget
var budget = budgetCtrl.getBudget();
//3. Display the bugdet on the UI
UICtrl.displayBudget(budget);
};
var updatePercentages = function()
{
//1. Calculate the percentages in the budget model
budgetCtrl.calculatePercentages();
//2..Read percentages from the budget model
var percentages = budgetCtrl.getPercentages();
//3.. Update the UI with new percentages
UICtrl.displayPercentages(percentages);
}
var ctrlAddItem = function()
{
//1. Get the field input data
var inputs = UICtrl.getInputs();
if(inputs.description !== "" && !isNaN(inputs.amount) && inputs.amount > 0)
{
//2. Pass the data to the bugdet controller
var newItem = budgetCtrl.addItem(inputs.type, inputs.description, inputs.amount);
//3. Add the item to the UI and
UICtrl.addListItem(newItem, inputs.type);
//4. clear the input fields
UICtrl.clearFields();
//5.. Calculate and update bugdet
updateBudget();
//6..Update the percentages
updatePercentages();
}
};
var ctrlDeleteItem = function(event)
{
var itemId, splitId, type, Id;
itemId = event.target.parentNode.parentNode.parentNode.id;
if(itemId)
{
splitId = itemId.split('-');
type = splitId[0];
Id = parseInt(splitId[1]);
//1.. Delete item from the data structure
budgetCtrl.deleteItem(type, Id);
//2.. Delete the item from the UI
UICtrl.deleteListItem(itemId);
//3.. Update and show new bugdet
updateBudget();
//4..Update the percentages
updatePercentages();
}
};
return {
init: function()
{
console.log('Application has started');
UICtrl.displayMonth();
UICtrl.displayBudget(
{
budget: 0,
totalInc: 0,
totalExp: 0,
percentage: -1
});
setupEventListeners();
}
};
})(budgetCtrl, viewCtr);
appCtr.init();