Skip to content

Commit

Permalink
tp8 step 2
Browse files Browse the repository at this point in the history
  • Loading branch information
ctruchi committed Feb 14, 2025
1 parent 4aa86cd commit 327506f
Show file tree
Hide file tree
Showing 3 changed files with 100 additions and 0 deletions.
17 changes: 17 additions & 0 deletions tp8/src/main/kotlin/fmt/kotlin/fundamentals/Cellar.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package fmt.kotlin.fundamentals

data class Vineyard(
val cellars: List<Cellar>
) {

fun countBottles() = emptyMap<String, Int>()
}

data class Cellar(
val bottles: List<Bottle>
)

data class Bottle(
val name: String,
val year: Int
)
21 changes: 21 additions & 0 deletions tp8/src/main/kotlin/fmt/kotlin/fundamentals/MapExt.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package fmt.kotlin.fundamentals

/**
* Merge with [map] using [operation] to compute the new value.
*
* If one map have no entry for a key, operation is not called and the existing value is used.
*
* @param K the type of keys in the maps
* @param V the type of values in the maps
* @param map the map to merge with
* @param operation an operation to call on entry with a value in both map to compute the new value
* @return a new map with keys of both maps and values computed with [operation]
*/
fun <K, V> Map<K, V>.merge(map: Map<K, V>, operation: (V, V) -> V): Map<K, V> =
(keys + map.keys).associateWith { key ->
if (this[key] != null && map[key] != null) {
operation(this[key]!!, map[key]!!)
} else {
this[key] ?: map[key]!!
}
}
62 changes: 62 additions & 0 deletions tp8/src/test/kotlin/fmt/kotlin/fundamentals/VineyardTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package fmt.kotlin.fundamentals

import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import strikt.api.expectThat
import strikt.assertions.isEqualTo

class VineyardTest {

val vineyard = Vineyard(
listOf(
Cellar(
listOf(
Bottle("Coucheroy", 2005),
Bottle("Coucheroy", 2005),
Bottle("Coucheroy", 2015),
Bottle("Coucheroy", 2015),
Bottle("Pedesclaux", 2009),
Bottle("Pedesclaux", 2009),
Bottle("Pedesclaux", 2009),
)
),
Cellar(
listOf(
Bottle("Coucheroy", 2015),
Bottle("Coucheroy", 2015),
Bottle("Coucheroy", 2015),
Bottle("Pedesclaux", 2009),
Bottle("Pedesclaux", 2009),
Bottle("Talbot", 2009),
Bottle("Talbot", 2015),
Bottle("Pedesclaux", 2009),
)
),
Cellar(
listOf(
Bottle("Talbot", 2005),
Bottle("Talbot", 2005),
Bottle("Talbot", 2005),
Bottle("Talbot", 2005),
Bottle("Pedesclaux", 2009),
Bottle("Pedesclaux", 2009),
Bottle("Pedesclaux", 2009),
)
)
)
)


@Test
fun `should count bottles in all cellars`() {
val count = vineyard.countBottles()

expectThat(count).isEqualTo(
mapOf(
"Coucheroy" to 7,
"Pedesclaux" to 9,
"Talbot" to 6
)
)
}
}

0 comments on commit 327506f

Please sign in to comment.