Last active
April 29, 2024 02:50
-
-
Save geoand/d629f5d3911c11c695742ab61951e7f8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Method extension code | |
*/ | |
fun <T1, T2> Collection<T1>.combine(other: Iterable<T2>): List<Pair<T1, T2>> { | |
return combine(other, {thisItem: T1, otherItem: T2 -> Pair(thisItem, otherItem) }) | |
} | |
fun <T1, T2, R> Collection<T1>.combine(other: Iterable<T2>, transformer: (thisItem: T1, otherItem:T2) -> R): List<R> { | |
return this.flatMap { thisItem -> other.map { otherItem -> transformer(thisItem, otherItem) }} | |
} | |
/** | |
* Test code | |
*/ | |
import org.assertj.core.api.Assertions.assertThat | |
import org.jetbrains.spek.api.Spek | |
class ListCombineSpec : Spek({ | |
describe("list.combine") { | |
val first = listOf("Kotlin", "Groovy") | |
val second = setOf("rocks", "kicks-ass", "is awesome") | |
it("should return a list of Pair objects containing all combinations") { | |
val combinations = first.combine(second) | |
assertThat(combinations).containsOnly( | |
Pair("Kotlin", "rocks"), | |
Pair("Kotlin", "kicks-ass"), | |
Pair("Kotlin", "is awesome"), | |
Pair("Groovy", "rocks"), | |
Pair("Groovy", "kicks-ass"), | |
Pair("Groovy", "is awesome") | |
) | |
} | |
it("should return a list of strings that represent the joint strings of all combinations") { | |
val combinations = first.combine(second, {first, second -> "$first $second"}) | |
assertThat(combinations).containsOnly( | |
"Kotlin rocks", | |
"Kotlin kicks-ass", | |
"Kotlin is awesome", | |
"Groovy rocks", | |
"Groovy kicks-ass", | |
"Groovy is awesome" | |
) | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice