aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib
diff options
context:
space:
mode:
authorSebastien Castiel <sebastien@castiel.me>2023-12-06 19:50:56 -0500
committerSebastien Castiel <sebastien@castiel.me>2023-12-06 19:50:56 -0500
commit6ce2329f5ce20f8352e3ea15594f2532ab8a392c (patch)
treed8d5fc4697ec0e51cd0267d5c3ffa9d048076c68 /src/lib
parente747ec3ea02dd01e9ffa9e398e24e6939a5b738c (diff)
Reimbursements
Diffstat (limited to 'src/lib')
-rw-r--r--src/lib/balances.ts40
1 files changed, 40 insertions, 0 deletions
diff --git a/src/lib/balances.ts b/src/lib/balances.ts
index fa00640..54dea00 100644
--- a/src/lib/balances.ts
+++ b/src/lib/balances.ts
@@ -6,6 +6,12 @@ export type Balances = Record<
{ paid: number; paidFor: number; total: number }
>
+export type Reimbursement = {
+ from: Participant['id']
+ to: Participant['id']
+ amount: number
+}
+
export function getBalances(
expenses: NonNullable<Awaited<ReturnType<typeof getGroupExpenses>>>,
): Balances {
@@ -40,3 +46,37 @@ function divide(total: number, count: number, isLast: boolean): number {
return total - divide(total, count, false) * (count - 1)
}
+
+export function getSuggestedReimbursements(
+ balances: Balances,
+): Reimbursement[] {
+ const balancesArray = Object.entries(balances).map(
+ ([participantId, { total }]) => ({ participantId, total }),
+ )
+ balancesArray.sort((b1, b2) => b2.total - b1.total)
+ console.log(balancesArray)
+ const reimbursements: Reimbursement[] = []
+ while (balancesArray.length > 1) {
+ const first = balancesArray[0]
+ const last = balancesArray[balancesArray.length - 1]
+ const amount = Math.round(first.total * 100 + last.total * 100) / 100
+ if (first.total > -last.total) {
+ reimbursements.push({
+ from: last.participantId,
+ to: first.participantId,
+ amount: -last.total,
+ })
+ first.total = amount
+ balancesArray.pop()
+ } else {
+ reimbursements.push({
+ from: last.participantId,
+ to: first.participantId,
+ amount: first.total,
+ })
+ last.total = amount
+ balancesArray.shift()
+ }
+ }
+ return reimbursements
+}