Skip to content

Commit

Permalink
Update calculateExpenses.tsx
Browse files Browse the repository at this point in the history
  • Loading branch information
mikejensen0 committed Nov 22, 2023
1 parent 753f444 commit d0ebcd5
Showing 1 changed file with 26 additions and 26 deletions.
52 changes: 26 additions & 26 deletions helpers/calculateExpenses.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,34 +10,34 @@ type Transaction = {
};

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

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

// Calculate who owes or is owed how much
const transactions: Transaction[] = [];
Object.keys(totalSpent).forEach((creditor) => {
let amountOwed = totalSpent[creditor] - averageAmount;
// 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 && averageAmount != totalSpent[creditor]) {
const settleAmount = Math.min(amountOwed, averageAmount - totalSpent[debitor]);
transactions.push({ to: creditor, from: debitor, amount: settleAmount });
totalSpent[creditor] -= settleAmount;
totalSpent[debitor] += settleAmount;
amountOwed -= settleAmount;
}
});
}
});
if (amountOwed > 0) {
Object.keys(totalSpent).forEach((debitor) => {
if (creditor !== debitor && totalSpent[debitor] < averageAmount && averageAmount != totalSpent[creditor]) {
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;
return transactions;
};

0 comments on commit d0ebcd5

Please sign in to comment.