Skip to content

Commit

Permalink
Added collectFirst to Chain and NonEmptyChain
Browse files Browse the repository at this point in the history
  • Loading branch information
LMnet committed Apr 17, 2019
1 parent 65bee09 commit 92fc8b3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
17 changes: 17 additions & 0 deletions core/src/main/scala/cats/data/Chain.scala
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,23 @@ sealed abstract class Chain[+A] {
else acc
}

/**
* Finds the first element of this `Chain` for which the given partial
* function is defined, and applies the partial function to it.
*/
final def collectFirst[B](pf: PartialFunction[A, B]): Option[B] = {
var result: Option[B] = None
foreachUntil { a =>
// trick from TraversableOnce, used to avoid calling both isDefined and apply (or calling lift)
val x = pf.applyOrElse(a, sentinel)
if (x.asInstanceOf[AnyRef] ne sentinel) {
result = Some(x.asInstanceOf[B])
true
} else false
}
result
}

/**
* Remove elements not matching the predicate
*/
Expand Down
6 changes: 6 additions & 0 deletions core/src/main/scala/cats/data/NonEmptyChain.scala
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,12 @@ class NonEmptyChainOps[A](private val value: NonEmptyChain[A]) extends AnyVal {
*/
final def collect[B](pf: PartialFunction[A, B]): Chain[B] = toChain.collect(pf)

/**
* Finds the first element of this `NonEmptyChain` for which the given partial
* function is defined, and applies the partial function to it.
*/
final def collectFirst[B](pf: PartialFunction[A, B]): Option[B] = toChain.collectFirst(pf)

/**
* Filters all elements of this chain that do not satisfy the given predicate.
*/
Expand Down

0 comments on commit 92fc8b3

Please sign in to comment.