scala-collection-compat icon indicating copy to clipboard operation
scala-collection-compat copied to clipboard

add `distinctBy`

Open xuwei-k opened this issue 3 years ago • 1 comments

xuwei-k avatar Jul 08 '22 05:07 xuwei-k

🤔

--- 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()
+  }

xuwei-k avatar Aug 16 '22 22:08 xuwei-k

🤔

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.

stewSquared avatar Jun 05 '23 20:06 stewSquared

First pass here: https://github.com/scala/scala-collection-compat/pull/602

alexklibisz avatar Jun 10 '23 02:06 alexklibisz