Skip to content

Commit

Permalink
Helper function for calculating expenses
Browse files Browse the repository at this point in the history
Assuming the following expenses:
    { resident: 'Person 1', amount: 100 },
    { resident: 'Person 2', amount: 40 },
    { resident: 'Person 3', amount: 60 },
    { resident: 'Person 4', amount: 0 },
then
Person 2 owes Person 1 $10
Person 4 owes Person 1 $40
Person 4 owes Person 3 $10
  • Loading branch information
mikejensen0 committed Nov 1, 2023
1 parent 847b7c7 commit 448d5ea
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions app/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 448d5ea

Please sign in to comment.