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 Ior.fromOptions #567

Merged
merged 1 commit into from
Oct 15, 2015
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
22 changes: 22 additions & 0 deletions core/src/main/scala/cats/data/Ior.scala
Original file line number Diff line number Diff line change
Expand Up @@ -169,4 +169,26 @@ sealed trait IorFunctions {
def left[A, B](a: A): A Ior B = Ior.Left(a)
def right[A, B](b: B): A Ior B = Ior.Right(b)
def both[A, B](a: A, b: B): A Ior B = Ior.Both(a, b)

/**
* Create an `Ior` from two Options if at least one of them is defined.
*
* @param oa an element (optional) for the left side of the `Ior`
* @param ob an element (optional) for the right side of the `Ior`
*
* @return `None` if both `oa` and `ob` are `None`. Otherwise `Some` wrapping
* an [[Ior.Left]], [[Ior.Right]], or [[Ior.Both]] if `oa`, `ob`, or both are
* defined (respectively).
*/
def fromOptions[A, B](oa: Option[A], ob: Option[B]): Option[A Ior B] =
oa match {
case Some(a) => ob match {
case Some(b) => Some(Ior.Both(a, b))
case None => Some(Ior.Left(a))
}
case None => ob match {
case Some(b) => Some(Ior.Right(b))
case None => None
}
}
}
15 changes: 15 additions & 0 deletions tests/src/test/scala/cats/tests/IorTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,19 @@ class IorTests extends CatsSuite {
i.append(j).right should === (i.right.map(_ + j.right.getOrElse("")).orElse(j.right))
}
}

test("fromOptions left/right consistent with input options"){
forAll { (oa: Option[String], ob: Option[Int]) =>
val x = Ior.fromOptions(oa, ob)
x.flatMap(_.left) should === (oa)
x.flatMap(_.right) should === (ob)
}
}

test("Option roundtrip"){
forAll { ior: String Ior Int =>
val iorMaybe = Ior.fromOptions(ior.left, ior.right)
iorMaybe should === (Some(ior))
}
}
}