-
Notifications
You must be signed in to change notification settings - Fork 0
/
budgetController.js
128 lines (99 loc) · 3.52 KB
/
budgetController.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
var budgetController = (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(cur){
sum += cur.value;
})
data.totals[type] = sum;
};
var data = {
allItems:{
exp: [],
inc: []
},
totals: {
exp: 0,
inc: 0
},
budget: 0,
percentage: -1 // -1 = non existant
};
return {
addItem: function(type, des, val){
var newItem, ID;
if (data.allItems[type].length > 0) {
ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
} else {
ID = 0;
}
if (type === 'exp'){
newItem = new Expense(ID, des, val);
} else if (type === 'inc'){
newItem = new Income(ID, des, val);
}
data.allItems[type].push(newItem);
return newItem;
},
deleteItem: function(type, id){
var ids, index;
ids = data.allItems[type].map(function(current){
return current.id;
});
index = ids.indexOf(id);
if (index !== -1) {
data.allItems[type].splice(index, 1);
}
},
calculateBudget: function(){
calculateTotal('exp');
calculateTotal('inc');
data.budget = data.totals.inc - data.totals.exp;
if (data.totals.inc > 0) {
data.percentage = Math.round((data.totals.exp / data.totals.inc) * 100)
} else {
data.percentage = -1;
}
},
calculatePercentages: function(){
data.allItems.exp.forEach(function(cur){
cur.calcPercentage(data.totals.inc);
});
},
getPercentages: function(){
var allPerc;
allPerc = data.allItems.exp.map(function(cur){
return cur.getPercentage();
});
return allPerc;
},
getBudget: function(){
return {
budget: data.budget,
totalInc: data.totals.inc,
totalExp: data.totals.exp,
percentage: data.percentage
}
}
};
})();