Skip to content

Commit

Permalink
Merge pull request #16 from andreasalstrup/CalculateExpensesHelperFun…
Browse files Browse the repository at this point in the history
…ction

Calculate expenses helper function
  • Loading branch information
andreasalstrup authored Nov 3, 2023
2 parents 677356e + 62bb5d6 commit 0e2fa90
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions helpers/calculateExpenses.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
type Expense = {
resident: string;
amount: number;
};

type Transaction = {
from: string;
to: string;
amount: number;
};

export const calculateExpenses = (expenses: Expense[]): Transaction[] => {
// Calculate total spent by each resident
const totalSpent: { [name: string]: number } = {};
expenses.forEach((expense) => {
totalSpent[expense.resident] = (totalSpent[expense.resident] || 0) + expense.amount;
});

// Calculate the average amount spent by all residents
const numResidents = Object.keys(totalSpent).length;
const totalAmountSpent = Object.values(totalSpent).reduce((total, amount) => total + amount, 0);
const averageAmount = totalAmountSpent / numResidents;

// Calculate who owes or is owed how much
const transactions: Transaction[] = [];
Object.keys(totalSpent).forEach((creditor) => {
let amountOwed = totalSpent[creditor] - averageAmount;

if (amountOwed > 0) {
Object.keys(totalSpent).forEach((debitor) => {
if (creditor !== debitor && totalSpent[debitor] < averageAmount) {
const settleAmount = Math.min(amountOwed, averageAmount - totalSpent[debitor]);
transactions.push({ to: creditor, from: debitor, amount: settleAmount });
totalSpent[creditor] -= settleAmount;
totalSpent[debitor] += settleAmount;
amountOwed -= settleAmount;
}
});
}
});

return transactions;
};

0 comments on commit 0e2fa90

Please sign in to comment.