Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add updateWith method to NonEmptyMap #2592

Merged
merged 7 commits into from
Nov 6, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions core/src/main/scala/cats/data/NonEmptyMapImpl.scala
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,15 @@ sealed class NonEmptyMapOps[K, A](val value: NonEmptyMap[K, A]) {
*/
def lookup(k: K): Option[A] = toSortedMap.get(k)

/**
* Applies f to the value stored at k. If lookup misses, does nothing.
*/
def updateWith(k: K)(f: A => A): NonEmptyMap[K, A] =
lookup(k) match {
case Some(v) => add((k, f(v)))
case None => value
}

/**
* Returns a `SortedSet` containing all the keys of this map.
*/
Expand Down
18 changes: 18 additions & 0 deletions tests/src/test/scala/cats/tests/NonEmptyMapSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -209,4 +209,22 @@ class NonEmptyMapSuite extends CatsSuite {
nem.toNel should ===(NonEmptyList.fromListUnsafe(nem.toSortedMap.toList))
}
}

test("NonEmptyMap#updateWith identity should be a no-op") {
forAll { (nem: NonEmptyMap[String, Int], i: (String, Int)) =>
nem.add(i) should ===(nem.add(i).updateWith(i._1)(identity))
nasadorian marked this conversation as resolved.
Show resolved Hide resolved
}
}

test("NonEmptyMap#updateWith on existing value should behave like Option#map on the same value") {
forAll { (nem: NonEmptyMap[String, Int], i: (String, Int)) =>
nem.add(i).lookup(i._1).map(_ + 1) should ===(nem.add(i).updateWith(i._1)(_ + 1).lookup(i._1))
}
}

test("NonEmptyMap#updateWith should not act when key is missing") {
val single = NonEmptyMap[String, Int](("here", 1), SortedMap())
single.lookup("notHere") should ===(single.updateWith("notHere")(_ => 1).lookup("notHere"))
}

}