From d0ebcd587898201833fa7b80b7454ca7f9749dfc Mon Sep 17 00:00:00 2001 From: Mike Jensen Date: Wed, 22 Nov 2023 08:45:10 +0100 Subject: [PATCH] Update calculateExpenses.tsx --- helpers/calculateExpenses.tsx | 52 +++++++++++++++++------------------ 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/helpers/calculateExpenses.tsx b/helpers/calculateExpenses.tsx index c84ce79..605889c 100644 --- a/helpers/calculateExpenses.tsx +++ b/helpers/calculateExpenses.tsx @@ -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; }; \ No newline at end of file