Skip to content

Commit

Permalink
Merge pull request #287 from lavrov/master
Browse files Browse the repository at this point in the history
Add filterKeys extension method to MapView
  • Loading branch information
julienrf authored Jan 6, 2020
2 parents 9fdf357 + db1d09b commit 83c9cef
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,12 @@ class TraversableExtensionMethods[A](private val self: c.Traversable[A]) extends
class MapViewExtensionMethods[K, V, C <: scala.collection.Map[K, V]](
private val self: IterableView[(K, V), C])
extends AnyVal {

def mapValues[W, That](f: V => W)(
implicit bf: CanBuildFrom[IterableView[(K, V), C], (K, W), That]): That =
self.map[(K, W), That] { case (k, v) => (k, f(v)) }

def filterKeys[That](p: K => Boolean)(
implicit bf: CanBuildFrom[IterableView[(K, V), C], (K, V), That]): That =
self.collect[(K, V), That] { case (k, v) if p(k) => (k, v) }
}
8 changes: 8 additions & 0 deletions compat/src/test/scala/test/scala/collection/ViewTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,12 @@ class ViewTest {
assertEquals(oldStyle.toMap, newStyle.toMap)
}

@Test
def filterKeys: Unit = {
val m = Map("a" -> 1, "b" -> 2, "c" -> 3)
val oldStyle = m.filterKeys(_ > "a")
val newStyle = m.view.filterKeys(_ > "a")
assertEquals(oldStyle.toMap, newStyle.toMap)
}

}

0 comments on commit 83c9cef

Please sign in to comment.