From 04db1f4234a64407fed497eaec978e4657c34104 Mon Sep 17 00:00:00 2001 From: Alex Klibisz Date: Thu, 15 Jun 2023 09:40:51 -0400 Subject: [PATCH] Add implementation of distinctBy (#602) --- .../scala/collection/compat/PackageShared.scala | 13 +++++++++++++ .../test/scala/collection/CollectionTest.scala | 7 +++++++ 2 files changed, 20 insertions(+) diff --git 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 index 4bd70b48..8e12de82 100644 --- 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 @@ -564,6 +564,19 @@ class TraversableLikeExtensionMethods[A, Repr](private val self: c.GenTraversabl } map.toMap } + + 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.contains(key)) { + builder += element + keys += key + } + } + builder.result() + } } class TrulyTraversableLikeExtensionMethods[El1, Repr1]( diff --git a/compat/src/test/scala/test/scala/collection/CollectionTest.scala b/compat/src/test/scala/test/scala/collection/CollectionTest.scala index 733c070b..4136a10b 100644 --- a/compat/src/test/scala/test/scala/collection/CollectionTest.scala +++ b/compat/src/test/scala/test/scala/collection/CollectionTest.scala @@ -186,4 +186,11 @@ class CollectionTest { assertTrue(List(1, 2, 3).lengthIs >= 2) assertTrue(List(1, 2, 3).lengthIs > 2) } + + @Test + def testDistinctBy(): Unit = { + assertEquals(List(1, 2, 3).distinctBy(_ % 2 == 0), List(1, 2)) + assertEquals(List(3, 1, 2).distinctBy(_ % 2 == 0), List(3, 2)) + assertEquals(List.empty[Int].distinctBy(_ % 2 == 0), List.empty) + } }