diff --git a/src/lib/balances.ts b/src/lib/balances.ts index 74eae78..70fea3f 100644 --- a/src/lib/balances.ts +++ b/src/lib/balances.ts @@ -82,13 +82,29 @@ export function getPublicBalances(reimbursements: Reimbursement[]): Balances { return balances } +/** + * A comparator that is stable across reimbursements. + * This ensures that a participant executing a suggested reimbursement + * does not result in completely new repayment suggestions. + */ +function compareBalancesForReimbursements(b1: any, b2: any): number { + // positive balances come before negative balances + if (b1.total > 0 && 0 > b2.total) { + return -1 + } else if (b2.total > 0 && 0 > b1.total) { + return 1 + } + // if signs match, sort based on userid + return b1.participantId < b2.participantId ? -1 : 1 +} + export function getSuggestedReimbursements( balances: Balances, ): Reimbursement[] { const balancesArray = Object.entries(balances) .map(([participantId, { total }]) => ({ participantId, total })) .filter((b) => b.total !== 0) - balancesArray.sort((b1, b2) => b2.total - b1.total) + balancesArray.sort(compareBalancesForReimbursements) const reimbursements: Reimbursement[] = [] while (balancesArray.length > 1) { const first = balancesArray[0]