Skip to content

Instantly share code, notes, and snippets.

@vriznyk-allset
Last active January 23, 2021 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vriznyk-allset/f66f761f423e6c182f61079697858837 to your computer and use it in GitHub Desktop.
Save vriznyk-allset/f66f761f423e6c182f61079697858837 to your computer and use it in GitHub Desktop.
data class Entity(
val properties: Map<String, String>,
val count: Int
)
val origin = listOf(
Entity(
mapOf(
"namespace1" to "first1",
"namespace2" to "first2"
),
1
),
Entity(
mapOf(
"namespace2" to "first2",
"namespace1" to "first1",
),
1
),
Entity(mapOf(), 10),
Entity(mapOf(), 10),
Entity(mapOf("namespace" to "first"), 1),
Entity(mapOf("namespace" to "first"), 1),
Entity(mapOf("namespace" to "second"), 2),
Entity(mapOf("namespace" to "second"), 2),
Entity(mapOf("namespace" to "third"), 3),
Entity(mapOf("namespace" to "third"), 3),
)
val expected = listOf(
Entity(
mapOf(
"namespace1" to "first1",
"namespace2" to "first2"
),
2
),
Entity(mapOf("namespace" to "first"), 2),
Entity(mapOf("namespace" to "third"), 6),
Entity(mapOf("namespace" to "second"), 4),
Entity(mapOf(), 20),
)
@Test
fun mergeEntities() {
val actual = origin
.asSequence()
.map { mapOf(it.properties to it) }
.reduce { acc, element ->
val result = acc.toMutableMap()
element.forEach { (key, value) ->
acc[key]?.let {
result[key] = it.copy(count = it.count + value.count)
} ?: run {
result[key] = value
}
}
result
}
.map { it.value }
.toList()
println("expected = $expected")
println("actual = $actual")
assertTrue(
expected.size == actual.size
&& expected.containsAll(actual)
&& actual.containsAll(expected)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment