Skip to content

Commit 327506f

Browse files
committed
tp8 step 2
1 parent 4aa86cd commit 327506f

File tree

3 files changed

+100
-0
lines changed

3 files changed

+100
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package fmt.kotlin.fundamentals
2+
3+
data class Vineyard(
4+
val cellars: List<Cellar>
5+
) {
6+
7+
fun countBottles() = emptyMap<String, Int>()
8+
}
9+
10+
data class Cellar(
11+
val bottles: List<Bottle>
12+
)
13+
14+
data class Bottle(
15+
val name: String,
16+
val year: Int
17+
)
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package fmt.kotlin.fundamentals
2+
3+
/**
4+
* Merge with [map] using [operation] to compute the new value.
5+
*
6+
* If one map have no entry for a key, operation is not called and the existing value is used.
7+
*
8+
* @param K the type of keys in the maps
9+
* @param V the type of values in the maps
10+
* @param map the map to merge with
11+
* @param operation an operation to call on entry with a value in both map to compute the new value
12+
* @return a new map with keys of both maps and values computed with [operation]
13+
*/
14+
fun <K, V> Map<K, V>.merge(map: Map<K, V>, operation: (V, V) -> V): Map<K, V> =
15+
(keys + map.keys).associateWith { key ->
16+
if (this[key] != null && map[key] != null) {
17+
operation(this[key]!!, map[key]!!)
18+
} else {
19+
this[key] ?: map[key]!!
20+
}
21+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package fmt.kotlin.fundamentals
2+
3+
import org.junit.jupiter.api.Assertions.*
4+
import org.junit.jupiter.api.Test
5+
import strikt.api.expectThat
6+
import strikt.assertions.isEqualTo
7+
8+
class VineyardTest {
9+
10+
val vineyard = Vineyard(
11+
listOf(
12+
Cellar(
13+
listOf(
14+
Bottle("Coucheroy", 2005),
15+
Bottle("Coucheroy", 2005),
16+
Bottle("Coucheroy", 2015),
17+
Bottle("Coucheroy", 2015),
18+
Bottle("Pedesclaux", 2009),
19+
Bottle("Pedesclaux", 2009),
20+
Bottle("Pedesclaux", 2009),
21+
)
22+
),
23+
Cellar(
24+
listOf(
25+
Bottle("Coucheroy", 2015),
26+
Bottle("Coucheroy", 2015),
27+
Bottle("Coucheroy", 2015),
28+
Bottle("Pedesclaux", 2009),
29+
Bottle("Pedesclaux", 2009),
30+
Bottle("Talbot", 2009),
31+
Bottle("Talbot", 2015),
32+
Bottle("Pedesclaux", 2009),
33+
)
34+
),
35+
Cellar(
36+
listOf(
37+
Bottle("Talbot", 2005),
38+
Bottle("Talbot", 2005),
39+
Bottle("Talbot", 2005),
40+
Bottle("Talbot", 2005),
41+
Bottle("Pedesclaux", 2009),
42+
Bottle("Pedesclaux", 2009),
43+
Bottle("Pedesclaux", 2009),
44+
)
45+
)
46+
)
47+
)
48+
49+
50+
@Test
51+
fun `should count bottles in all cellars`() {
52+
val count = vineyard.countBottles()
53+
54+
expectThat(count).isEqualTo(
55+
mapOf(
56+
"Coucheroy" to 7,
57+
"Pedesclaux" to 9,
58+
"Talbot" to 6
59+
)
60+
)
61+
}
62+
}

0 commit comments

Comments
 (0)