From 9c09272bb91726f0dbcbcd4b6b0b1f4893a8b4dd Mon Sep 17 00:00:00 2001 From: Karun Japhet Date: Fri, 10 Feb 2023 13:28:13 +0530 Subject: [PATCH] Split processing of totals out from printing the report --- .../com/nelkinda/training/ExpenseReport.kt | 22 +++++++------------ 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/expensereport-kotlin/src/main/kotlin/com/nelkinda/training/ExpenseReport.kt b/expensereport-kotlin/src/main/kotlin/com/nelkinda/training/ExpenseReport.kt index ee2fc0f6..232e0355 100644 --- a/expensereport-kotlin/src/main/kotlin/com/nelkinda/training/ExpenseReport.kt +++ b/expensereport-kotlin/src/main/kotlin/com/nelkinda/training/ExpenseReport.kt @@ -7,24 +7,18 @@ class ExpenseReport( private val dateProvider: () -> Date = { Date() } ) { fun printReport(expenses: List) { - var total = 0 - var mealExpenses = 0 - printer("Expenses ${dateProvider()}") - for (expense in expenses) { - if (expense.type == ExpenseType.DINNER || expense.type == ExpenseType.BREAKFAST) { - mealExpenses += expense.amount - } - - val mealOverExpensesMarker = expense.overLimitMarker() - - printer(expense.type.reportName + "\t" + expense.amount + "\t" + mealOverExpensesMarker) - - total += expense.amount + expenses.forEach { + printer(it.type.reportName + "\t" + it.amount + "\t" + it.overLimitMarker()) } - printer("Meal expenses: $mealExpenses") + val (mealExpenses, otherExpenses) = expenses + .partition { it.type == ExpenseType.DINNER || it.type == ExpenseType.BREAKFAST } + val mealExpenseTotal = mealExpenses.sumOf { it.amount } + val total = mealExpenseTotal + otherExpenses.sumOf { it.amount } + + printer("Meal expenses: $mealExpenseTotal") printer("Total expenses: $total") } }