Skip to content

Commit

Permalink
feature/add fold* to EitherOps (#1234)
Browse files Browse the repository at this point in the history
* feature/add fold* to EitherOps

* feature/add fold* to EitherOps

* feature/add test case with None

---------

Co-authored-by: Igor Fedorov <[email protected]>
  • Loading branch information
iyfedorov and Igor Fedorov authored Apr 9, 2024
1 parent f4e5623 commit 1c3699f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
25 changes: 25 additions & 0 deletions modules/core/ce2/src/test/scala/tofu/syntax/FEitherSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,31 @@ class FEitherSuite extends AnyWordSpec with Matchers {
}
}

"EitherFOps#foldIn" should {
"map left or right to C" in {
defaultRight.foldIn(_.length, c => c * c) mustBe Some(16)
defaultLeft.foldIn(c => c * c, _.length) mustBe Some(16)
}
}

"EitherFOps#foldF" should {
"map left or right to F[C]" in {
defaultRight.foldF(s => Some(s.length), c => Some(c * c)) mustBe Some(16)
defaultLeft.foldF(c => Some(c * c), s => Some(s.length)) mustBe Some(16)
}

"fold to None" in {
defaultRight.foldF(_ => None, _ => None) mustBe None
defaultLeft.foldF(_ => None, _ => None) mustBe None
}

"fold on None" in {
val emptyF = Option.empty[Either[String, Int]]
emptyF.foldF(_ => None, _ => None) mustBe None
emptyF.foldIn(_ => 1, _ => 1) mustBe None
}
}

"EitherFOps#ensure" should {

"return None" in {
Expand Down
8 changes: 8 additions & 0 deletions modules/kernel/src/main/scala/tofu/syntax/feither.scala
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,14 @@ object feither {
e.flatMap(_.wideLeft[L1].flatTraverse(f))
}

def foldIn[C](lMap: L => C, rMap: R => C)(implicit F: Functor[F]): F[C] = {
e.map(_.fold(lMap, rMap))
}

def foldF[C](lMap: L => F[C], rMap: R => F[C])(implicit F: Monad[F]): F[C] = {
e.flatMap(_.fold(lMap, rMap))
}

def swapF(implicit F: Functor[F]): F[Either[R, L]] = {
F.map(e)(_.swap)
}
Expand Down

0 comments on commit 1c3699f

Please sign in to comment.