Skip to content

Commit

Permalink
Add implementation of distinctBy (#602)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexklibisz authored Jun 15, 2023
1 parent c0ec12b commit 04db1f4
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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](
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit 04db1f4

Please sign in to comment.