Skip to content

Instantly share code, notes, and snippets.

@KaNiShi
Last active July 17, 2019 07:51
Show Gist options
  • Save KaNiShi/96afcdb8c8beb8a50eb8e098fcfac972 to your computer and use it in GitHub Desktop.
Save KaNiShi/96afcdb8c8beb8a50eb8e098fcfac972 to your computer and use it in GitHub Desktop.
inline fun <T> List<T>.reverseEach(action: (T) -> Unit) = listIterator(size).reverseEach(action)
inline fun <T, R> List<T>.reverseMap(transform: (T) -> R): List<R> = listIterator(size).reverseMap(transform)
inline fun <T, K, V> List<T>.reverseAssociate(transform: (T) -> Pair<K, V>): Map<K, V> = listIterator(size).reverseAssociate(transform)
inline fun <T> ListIterator<T>.reverseEach(action: (T) -> Unit) {
while(hasPrevious()) action(previous())
}
inline fun <T, R> ListIterator<T>.reverseMap(transform: (T) -> R): List<R> = reverseMapTo(ArrayList(nextIndex()), transform)
inline fun <T, R, C: MutableCollection<in R>> ListIterator<T>.reverseMapTo(destination: C, transform: (T) -> R): C {
while(hasPrevious()) destination.add(transform(previous()))
return destination
}
inline fun <T, K, V> ListIterator<T>.reverseAssociate(transform: (T) -> Pair<K, V>): Map<K, V> {
val size = previousIndex()
val capacity = when {
size < 3 -> size + 1
size < Int.MAX_VALUE shr 1 -> size + size / 3
else -> Int.MAX_VALUE
}
return reverseAssociateTo(LinkedHashMap(capacity), transform)
}
inline fun <T, K, V, M : MutableMap<in K, in V>> ListIterator<T>.reverseAssociateTo(destination: M, transform: (T) -> Pair<K, V>): M {
while (hasPrevious()) destination += transform(previous())
return destination
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment