Skip to content

Instantly share code, notes, and snippets.

@geoand
Last active April 29, 2024 02:50
Show Gist options
  • Save geoand/d629f5d3911c11c695742ab61951e7f8 to your computer and use it in GitHub Desktop.
Save geoand/d629f5d3911c11c695742ab61951e7f8 to your computer and use it in GitHub Desktop.
/**
* 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"
)
}
}
})
@kiotaku
Copy link

kiotaku commented Sep 10, 2017

nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment