-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (52 loc) · 2.69 KB
/
index.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
const transactionsArray = require('./transactions'); /* importing transactions from a different file */
const simplifyDebts = (transactions) => {
const entities = ['paidBy', 'paidFor'];
let targets = {}; /* targets is the object that stores entities and their values.
Values can be positive signalling debt and negative signalling credit { 'A' : 100 } */
let data = [];
transactions.forEach(transaction => {
let payingEntity = transaction[entities[0]];
let paidForEntites = Object.keys(transaction[entities[1]]); /* convert the keys into an array to make iterable */
if(paidForEntites.length == 1) {
let paidBy = { 'paidBy': paidForEntites[0] };
let paidFor = {'paidFor' : { [payingEntity] : transaction[entities[1]][paidForEntites[0]] } };
data.push(paidBy,paidFor);
return;
}
paidForEntites.forEach(paidEntity => {
if (targets[paidEntity])
targets[paidEntity] += transaction[entities[1]][paidEntity]; /* if entity exists , add value */
else
targets[paidEntity] = 0 + transaction[entities[1]][paidEntity];
if (targets[transaction[entities[0]]])
targets[transaction[entities[0]]] -= transaction[entities[1]][paidEntity];
else
targets[transaction[entities[0]]] = 0 - transaction[entities[1]][paidEntity];
});
})
let sortedArray = [];
for (var target in targets) {
sortedArray.push([target, targets[target]]); /* [ [ 'B', 0 ],[ 'F', 622 ]] */
}
while (sortedArray.filter((element) => !Boolean(element[1])).length != sortedArray.length) { /* loop runs till values of all the elements changes to 0 */
let paidFor = {};
let paidBy = {};
sortedArray.sort((a, b) => b[1] - a[1]); /* sort array to decreasing */
if (sortedArray[0][1] > -sortedArray[sortedArray.length - 1][1]) { /* if debt is greater than credit */
// paidBy[sortedArray[0][0]] = -sortedArray[sortedArray.length - 1][1]; /* add entry to the transaction { paidBy : { 'A' : 50 } } */
paidBy = { 'paidBy': sortedArray[0][0] }; // so a number that that is -ive is found which is not greater than the max element
paidFor[sortedArray[sortedArray.length - 1][0]] = -sortedArray[sortedArray.length - 1][1]; /* { paidFor: { A: 1204 } } */
sortedArray[0][1] += sortedArray[sortedArray.length - 1][1];
sortedArray[sortedArray.length - 1][1] = 0;
data.push(paidBy, { paidFor });
} else {
paidBy = { 'paidBy': sortedArray[0][0] }; // so a number that that is -ive is found which is not greater than the max element
paidFor[sortedArray[sortedArray.length - 1][0]] = sortedArray[0][1];
sortedArray[sortedArray.length - 1][1] += sortedArray[0][1];
sortedArray[0][1] = 0;
data.push(paidBy, { paidFor });
}
}
console.log(data);
}
simplifyDebts(transactionsArray);