forked from mettrr/be-tech-test-debt-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdebt.js
128 lines (96 loc) · 2.29 KB
/
debt.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
module.exports = {
init: function() {
// TODO:: Persist data in file or DB
// TODO:: Read at this stage..
},
append: function() {
// TODO:: Add record to file or DB
},
data: [],
// Add a debt
add: function(from, to, amount) {
// TODO:: Search and aggregate debts..
if(!from || !to || !parseFloat(amount)) {
return false;
}
var total = 0;
var count = 0;
for(x in this.data) {
// Check existing to this name
if(this.data[x][0] == from && this.data[x][1] == to) {
total += this.data[x][2];
count++;
}
// Check existing from this name
if(this.data[x][1] == from && this.data[x][0] == to) {
total -= this.data[x][2];
count++;
}
}
this.data.push([ from , to , parseFloat(amount), new Date().getTime() ]);
total += parseFloat(amount);
count++;
// Check if all settled between 2 users
if(total == 0) {
// TODO::
// Clear existing records?
// Keep for reference?
}
// TODO:: More readable format perhaps?
// Debt model should be an object with easier lookup?
/*
this.data.push({
from: from,
to: to,
amount: amount,
time: new Date().getTime()
});
*/
// console.log(this.data);
// Return total money owed between 2 users
return total;
},
// Read single
read: function(name) {
if(!name) {
// No person specified
return false;
}
var res_owe = {};
var res_owed = {};
for(x in this.data) {
if(this.data[x][0] == name) {
// This person owes somebody, aggregate..
if(res_owed[this.data[x][1]]) {
res_owed[this.data[x][1]] += this.data[x][2];
} else {
res_owed[this.data[x][1]] = this.data[x][2];
}
} else if(this.data[x][1] == name) {
if(res_owe[this.data[x][0]]) {
res_owe[this.data[x][0]] += this.data[x][2];
} else {
res_owe[this.data[x][0]] = this.data[x][2];
}
// Somebody owes this person
} else {
// Between other people
}
}
// if(!res_owe.length && !res_owed.length) {
// Specified person not found
// return false;
// }
return {
owe: res_owe,
owed: res_owed,
};
},
// Get settle solution between all people
settle: function() {
// TODO::
// Iterate the data to merge debts..
// Recurcively?
// First sort?
}
}