From 3224dc7f1db77b865ca01ce9fb2574f56656edb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Sch=C3=BCrg?= Date: Mon, 29 Aug 2022 13:13:15 +0200 Subject: [PATCH] feat: add sum functions for Money collections --- .../java/de/tobiasschuerg/money/MoneyUtils.kt | 20 +++++++++++++++++++ .../de/tobiasschuerg/money/MoneyListTest.kt | 18 +++++++++++++++-- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/money/src/main/java/de/tobiasschuerg/money/MoneyUtils.kt b/money/src/main/java/de/tobiasschuerg/money/MoneyUtils.kt index daec31e..8a54ce9 100644 --- a/money/src/main/java/de/tobiasschuerg/money/MoneyUtils.kt +++ b/money/src/main/java/de/tobiasschuerg/money/MoneyUtils.kt @@ -3,3 +3,23 @@ package de.tobiasschuerg.money fun Money.toFloat(): Float = amount.toFloat() fun Money.toDouble(): Double = amount.toDouble() + +/** + * Sum all amounts on the collection. + * Will throw if currencies does not match. + * @see [sum(currency)] + */ +fun Collection.sum(): Money { + return fold(Money.ZERO) { acc, money -> + if (money.isZero()) acc else acc + money + } +} + +/** + * Sum all amounts on the collection and auto apply currency conversion. + */ +fun Collection.sum(currency: Currency): Money { + return fold(Money.ZERO) { acc, money -> + if (money.isZero()) acc else acc + money.convertInto(currency) + } +} diff --git a/money/src/test/java/de/tobiasschuerg/money/MoneyListTest.kt b/money/src/test/java/de/tobiasschuerg/money/MoneyListTest.kt index 2b79f1a..f0e52c5 100644 --- a/money/src/test/java/de/tobiasschuerg/money/MoneyListTest.kt +++ b/money/src/test/java/de/tobiasschuerg/money/MoneyListTest.kt @@ -1,5 +1,6 @@ package de.tobiasschuerg.money +import de.tobiasschuerg.money.Currencies.EURO import org.junit.Assert import org.junit.Test @@ -8,8 +9,8 @@ import org.junit.Test */ class MoneyListTest { - private val currency = Currency("EUR", "Euro", 1.0) - private val list = MoneyList(currency) + private val currency = EURO + private val list = MoneyList(EURO) init { list.add(Money(3, currency)) @@ -58,4 +59,17 @@ class MoneyListTest { Assert.assertEquals(1, sublist.min()?.amount?.intValueExact()) Assert.assertEquals(6, sublist.max()?.amount?.intValueExact()) } + + @Test + fun `test that sum of same currencies is calculated correctly`() { + val result = list.sum() + Assert.assertEquals(45.00, result.amount.toDouble(), 0.01) + } + + @Test + fun `test that sum of different currencies is calculated correctly`() { + val list2: List = list.plus(Money(5.37, Currencies.USDOLLAR)) + val result = list2.sum(EURO) + Assert.assertEquals(49.93, result.amount.toDouble(), 0.01) + } }