Skip to content

Commit

Permalink
add zipby
Browse files Browse the repository at this point in the history
  • Loading branch information
FunkyMuse committed Oct 5, 2021
1 parent e3bf7bf commit 736b51b
Showing 1 changed file with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.crazylegend.collections
import kotlin.collections.associateBy

/**
* Created by Hristijan, date 10/5/21
*/
fun <FIRST_LIST_TYPE, SECOND_LIST_TYPE, FIRST_LIST_TRANSFORMER, SECOND_LIST_TRANSFORMER, RETURN_TYPE>
Iterable<FIRST_LIST_TYPE>.zipBy(
other: Iterable<SECOND_LIST_TYPE>,
firstListTransformer: (FIRST_LIST_TYPE) -> FIRST_LIST_TRANSFORMER,
secondListTransformer: (SECOND_LIST_TYPE) -> SECOND_LIST_TRANSFORMER,
pairPredicate: (first: FIRST_LIST_TYPE?, second: SECOND_LIST_TYPE?) -> RETURN_TYPE?
): List<RETURN_TYPE> {
val firstByKey: Map<FIRST_LIST_TRANSFORMER, FIRST_LIST_TYPE> = associateBy {
firstListTransformer(it)
}
val secondByKey: Map<SECOND_LIST_TRANSFORMER, SECOND_LIST_TYPE> = other.associateBy {
secondListTransformer(it)
}
val resultList = (firstByKey.keys + secondByKey.keys).map { (firstByKey[it]) to (secondByKey[it]) }
return resultList.asSequence().mapNotNull {
val firstPair = it.first
val secondPair = it.second
pairPredicate(firstPair, secondPair)
}.toList()
}

0 comments on commit 736b51b

Please sign in to comment.