scala-collection-compat
scala-collection-compat copied to clipboard
add `distinctBy`
🤔
--- a/compat/src/main/scala-2.11_2.12/scala/collection/compat/PackageShared.scala
+++ b/compat/src/main/scala-2.11_2.12/scala/collection/compat/PackageShared.scala
@@ -467,6 +467,20 @@ private object SizeCompareImpl {
class TraversableLikeExtensionMethods[A, Repr](private val self: c.GenTraversableLike[A, Repr])
extends AnyVal {
+
+ def distinctBy[B, That](f: A => B)(implicit cbf: CanBuildFrom[Repr, A, That]): That = {
+ val builder = cbf()
+ val keys = collection.mutable.Set.empty[B]
+ for (element <- self) {
+ val key = f(element)
+ if (!keys(key)) {
+ builder += element
+ keys += key
+ }
+ }
+ builder.result()
+ }
🤔
Is this is all there is to it (plus tests)? I'm happy to make the PR as part of the current spree; it just seems odd that it wouldn't be done yet.
First pass here: https://github.com/scala/scala-collection-compat/pull/602