Skip to content

Commit

Permalink
feat: add sum functions for Money collections
Browse files Browse the repository at this point in the history
  • Loading branch information
tobiasschuerg committed Aug 29, 2022
1 parent 1e988cf commit 3224dc7
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
20 changes: 20 additions & 0 deletions money/src/main/java/de/tobiasschuerg/money/MoneyUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<Money>.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<Money>.sum(currency: Currency): Money {
return fold(Money.ZERO) { acc, money ->
if (money.isZero()) acc else acc + money.convertInto(currency)
}
}
18 changes: 16 additions & 2 deletions money/src/test/java/de/tobiasschuerg/money/MoneyListTest.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package de.tobiasschuerg.money

import de.tobiasschuerg.money.Currencies.EURO
import org.junit.Assert
import org.junit.Test

Expand All @@ -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))
Expand Down Expand Up @@ -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<Money> = list.plus(Money(5.37, Currencies.USDOLLAR))
val result = list2.sum(EURO)
Assert.assertEquals(49.93, result.amount.toDouble(), 0.01)
}
}

0 comments on commit 3224dc7

Please sign in to comment.