Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Calculate expenses helper function #16

Merged
merged 5 commits into from
Nov 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
};