Skip to content

Commit

Permalink
Merge pull request #567 from ceedubs/ior-fromoptions
Browse files Browse the repository at this point in the history
Add Ior.fromOptions
  • Loading branch information
adelbertc committed Oct 15, 2015
2 parents a7b845e + 329ba90 commit f69b3e1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
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))
}
}
}

0 comments on commit f69b3e1

Please sign in to comment.