Skip to content

Commit

Permalink
feat: add mapCollection
Browse files Browse the repository at this point in the history
  • Loading branch information
Idane committed Jul 19, 2022
1 parent 1bca6cf commit 2cba93f
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 6 deletions.
18 changes: 18 additions & 0 deletions shapeshift/src/main/kotlin/dev/krud/shapeshift/ShapeShift.kt
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,24 @@ class ShapeShift internal constructor(
return toObject
}

/**
* Map [fromObjects] to a list of [toClazz] objects
*/
fun <From : Any, To : Any> mapCollection(fromObjects: Collection<From>, toClazz: Class<To>): List<To> {
val toObjects = ArrayList<To>(fromObjects.size)
for (fromObject in fromObjects) {
toObjects.add(map(fromObject, toClazz))
}
return toObjects
}

/**
* Map [fromObjects] to a list of [toClazz] objects
*/
inline fun <From : Any, reified To : Any> mapCollection(fromObjects: Collection<From>): List<To> {
return mapCollection(fromObjects, To::class.java)
}

private fun <From : Any, To : Any> mapField(fromObject: From, toObject: To, resolvedMappedField: ResolvedMappedField) {
val fromPair = getFieldInstanceByNodes(resolvedMappedField.mapFromCoordinates, fromObject, SourceType.FROM) ?: return
val toPair = getFieldInstanceByNodes(resolvedMappedField.mapToCoordinates, toObject, SourceType.TO) ?: return
Expand Down
23 changes: 23 additions & 0 deletions shapeshift/src/test/kotlin/dev/krud/shapeshift/ShapeShiftTests.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,29 @@ internal class ShapeShiftTests {

@Nested
inner class Scenarios {
@Test
internal fun `mapCollection with set of objects`() {
val shapeShift = ShapeShiftBuilder()
.withMapping<GenericFrom, GenericTo> {
GenericFrom::long mappedTo GenericTo::long
}
.build()
val result: List<GenericTo> = shapeShift.mapCollection(
setOf(
GenericFrom(1L),
GenericFrom(2L),
GenericFrom(3L)
)
)
val expected = listOf(
GenericTo(1L),
GenericTo(2L),
GenericTo(3L)
)
expectThat(result)
.isEqualTo(expected)
}

@Test
internal fun `multiple mapped fields on field`() {
val result = shapeShift.map(FromWithMultipleMappedFields(), MultipleFieldTo::class.java)
Expand Down
12 changes: 6 additions & 6 deletions shapeshift/src/test/kotlin/dev/krud/shapeshift/_fixtures.kt
Original file line number Diff line number Diff line change
Expand Up @@ -182,13 +182,13 @@ internal class TypeTransformerFrom {
val long: Long = 1L
}

internal class GenericFrom {
var long: Long = 1L
}
internal data class GenericFrom(
val long: Long = 1L
)

internal class GenericTo {
var long: Long? = null
}
internal data class GenericTo(
val long: Long? = null
)

internal class StringTo {
var long: String? = null
Expand Down

0 comments on commit 2cba93f

Please sign in to comment.