scala / scala-library-next

backwards-binary-compatible Scala standard library additions
Apache License 2.0
67 stars 17 forks source link

Set method that returns all areas of a set intersection #184

Open Lasering opened 1 week ago

Lasering commented 1 week ago

When computing the set differences its very common to need access to all "areas" of a set intersection:

val existingLocationIds: Set[String] = ???
val newLocationIds: Set[String] = ???
val (removed, unchanged, added) = existingLocationIds.fullIntersection(newLocationIds)

This can be easily implemented with:

val unchanged = existingLocationsIds.intersect(newLocationIds)
val removed = existingLocationsIds.diff(unchanged)
val added = newLocationIds.diff(unchanged)

However this is not very performant, as we are iterating each set multiple times. Thus a performant method could be implemented. The name fullIntersection is just a placeholder, I'm sure there is a better name for this.

As an added bonus we could even take this one step further and have a fullIntersectionBy variant. In most cases this would be much more useful:

val existingLocations: Seq[Location] = ???
val newLocations: Seq[Location] = ???
val (removed, unchanged, added) = existingLocations.toSet.fullIntersectionBy(newLocations.toSet)(_.id)

Since List also has the intersect method we could also add it directly there:

existingLocations.fullIntersectionBy(newLocations)(_.id)