Created
November 12, 2021 20:36
-
-
Save otobrglez/05eb24ecc6ad4c4ced77d3de99fc9406 to your computer and use it in GitHub Desktop.
Detecting "addition" or "change" within two lists.
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
import java.util.UUID | |
sealed trait Change[V] extends Product { val value: V } | |
final case class Added[V](value: V) extends Change[V] | |
final case class Updated[V](value: V, prev: V) extends Change[V] | |
def changesWithKey[T, K](previous: Array[T], current: Array[T]) | |
(implicit key: T => K): Array[Change[T]] = { | |
val updates: Array[Change[T]] = for { | |
p <- previous; c <- current | |
r = Updated(p, c) if p != c && key(p) == key(c) | |
} yield r | |
(updates ++ current.filterNot(previous.contains(_)).map(Added(_))) | |
.distinctBy(change => key(change.value)) | |
} | |
/** | |
* Usage example. We have 2 arrays or "traffic-events" and we care about what event was "added" | |
* or what event was "changed" (i.e. status was updated or something similar) | |
*/ | |
type ID = UUID | |
sealed trait RawEvent extends Product { val id: ID } | |
final case class RoadClosure(street: String, id: ID = UUID.randomUUID()) extends RawEvent | |
final case class Accident(message: String, id: ID = UUID.randomUUID()) extends RawEvent | |
final case class Radar(id: ID = UUID.randomUUID()) extends RawEvent | |
val List(roadClosure: RoadClosure, radar: Radar, accident: Accident, roadClosure2: RoadClosure) = | |
List(RoadClosure("Main Street"), Radar(), Accident("Accident here"), | |
RoadClosure("Big closure here")) | |
val previous = Array(roadClosure2, radar, accident) | |
val current = Array(radar, accident.copy(message = "No more accident."), roadClosure2) | |
changesWithKey(previous, current)(_.id).mkString("\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment