-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest_utils.ts
75 lines (62 loc) · 2.5 KB
/
test_utils.ts
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
type SplitwiseInputPayees = { [payee: string]: number };
export interface SplitwiseInputItem {
paidBy: string;
paidFor: SplitwiseInputPayees;
}
function round(amount: number, decimals: number): number {
const val = Math.pow(10, decimals)
return Math.round(amount * val) / val;
}
function checkAmounts<T>(amount: number, amount1: number, decimals: number, targetBit = "==="): T {
amount = round(amount, decimals);
amount1 = round(amount1, decimals);
const res: T = eval(`${amount}
${targetBit}
${amount1}`);
return res;
}
/**
* Make sure we're owed what we spent for others
* @param reparts
* @param inputs
*/
export function checkBalance(reparts: [string, string, number][], inputs: SplitwiseInputItem[]) {
const getSumOwedFor = (getFor: string, wereOwed = true): number => {
return reparts.filter(([pfrom, pto, _pamount]: [string, string, number]) => {
return wereOwed ? pto === getFor : pfrom === getFor;
}).reduce((res: number, [_pfrom, _pto, pamount]: [string, string, number]) => {
return res + pamount;
}, 0);
};
const users: string[] = inputs.reduce((rf: string[], iff: SplitwiseInputItem) => {
const taAdd = Object.keys(iff.paidFor).concat([iff.paidBy]);
return rf.concat(taAdd.filter((tr: string) => rf.indexOf(tr) === -1));
}, []);
users.sort();
for (const user of users) {
const sortiePoche = inputs.filter((ex: SplitwiseInputItem) => ex.paidBy === user)
.reduce((res: number, item: SplitwiseInputItem) => {
const toAd: number = Object.keys(item.paidFor).reduce((rres: number, ramountKey: string) => {
return rres + item.paidFor[ramountKey]
}, 0);
return res + toAd;
}, 0);
const totalCost: number = inputs.reduce((res: number, ex: SplitwiseInputItem) => {
const targ = ex.paidFor[user];
if (targ) {
res += targ;
}
return res;
}, 0);
const eqData = sortiePoche > totalCost
? [getSumOwedFor(user), sortiePoche - totalCost]
: [getSumOwedFor(user, false), Math.abs(sortiePoche - totalCost)];
const eq = checkAmounts(eqData[0], eqData[1], 1);
console.log(`${user} ${eq} %o`, eqData);
if (!eq) {
if (Math.abs(eqData[0] - eqData[1]) > 1) {
throw new Error(`Wrong amount check: ${eqData[0]} !== ${eqData[1]}`);
}
}
}
}