Skip to content

Instantly share code, notes, and snippets.

@sitepodmatt
Created February 28, 2019 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sitepodmatt/abc23118efed18c5f9005a663738822a to your computer and use it in GitHub Desktop.
Save sitepodmatt/abc23118efed18c5f9005a663738822a to your computer and use it in GitHub Desktop.
Map diff util
sealed class MapDiffResult<T : Any,V : Any> {
data class Added<T : Any,V : Any>(val key : T, val v : V) : MapDiffResult<T, V>()
data class Removed<T : Any,V : Any>(val key : T, val oldValue : V) : MapDiffResult<T, V>()
data class Changed<T : Any,V : Any>(val key : T, val new : V, val old :V) : MapDiffResult<T, V>()
}
fun <K : Any,V : Any> Map<K,V>.diffMaps(to: Map<K,V>, isSame : (V, V?) -> Boolean = { v,v2 -> v == v2 }) : List<MapDiffResult<K, V>> {
val from = this
val changes = mutableListOf<MapDiffResult<K, V>>()
to.forEach { k, v ->
if(!from.containsKey(k)) {
changes.add(MapDiffResult.Added(k, v))
} else {
if(!isSame(v,from[k])) {
changes.add(MapDiffResult.Changed(k, v, from[k]!!))
}
}
}
from.forEach { k, v ->
if(!to.containsKey(k)) {
changes.add(MapDiffResult.Removed(k, v))
}
}
return changes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment