Created
February 28, 2019 08:42
-
-
Save sitepodmatt/abc23118efed18c5f9005a663738822a to your computer and use it in GitHub Desktop.
Map diff util
This file contains 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
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