Skip to content

Commit 04db1f4

Browse files
authored
Add implementation of distinctBy (#602)
1 parent c0ec12b commit 04db1f4

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

compat/src/main/scala-2.11_2.12/scala/collection/compat/PackageShared.scala

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -564,6 +564,19 @@ class TraversableLikeExtensionMethods[A, Repr](private val self: c.GenTraversabl
564564
}
565565
map.toMap
566566
}
567+
568+
def distinctBy[B, That](f: A => B)(implicit cbf: CanBuildFrom[Repr, A, That]): That = {
569+
val builder = cbf()
570+
val keys = collection.mutable.Set.empty[B]
571+
for (element <- self) {
572+
val key = f(element)
573+
if (!keys.contains(key)) {
574+
builder += element
575+
keys += key
576+
}
577+
}
578+
builder.result()
579+
}
567580
}
568581

569582
class TrulyTraversableLikeExtensionMethods[El1, Repr1](

compat/src/test/scala/test/scala/collection/CollectionTest.scala

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,4 +186,11 @@ class CollectionTest {
186186
assertTrue(List(1, 2, 3).lengthIs >= 2)
187187
assertTrue(List(1, 2, 3).lengthIs > 2)
188188
}
189+
190+
@Test
191+
def testDistinctBy(): Unit = {
192+
assertEquals(List(1, 2, 3).distinctBy(_ % 2 == 0), List(1, 2))
193+
assertEquals(List(3, 1, 2).distinctBy(_ % 2 == 0), List(3, 2))
194+
assertEquals(List.empty[Int].distinctBy(_ % 2 == 0), List.empty)
195+
}
189196
}

0 commit comments

Comments
 (0)