Skip to content

Commit

Permalink
Adds split to Seq[Result]
Browse files Browse the repository at this point in the history
Signed-off-by: Albert Pastrana <albert.pastrana@gmail.com>
  • Loading branch information
albertpastrana committed Apr 13, 2018
1 parent ba7c273 commit c826a13
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 8 deletions.
10 changes: 10 additions & 0 deletions result/src/main/scala/uscala/result/Result.scala
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,16 @@ object Result extends ResultFunctions {
a <- fa
} yield r += a
}.map(_.result())

def split(implicit bfe : CanBuildFrom[Nothing, E, M[E]], bfa : CanBuildFrom[Nothing, A, M[A]]): (M[E], M[A]) = {
val be = bfe()
val ba = bfa()
xs.foreach {
case Ok(v) => ba += v
case Fail(e) => be += e
}
(be.result, ba.result)
}
}

/**
Expand Down
30 changes: 22 additions & 8 deletions result/src/test/scala/uscala/result/ResultSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -284,15 +284,29 @@ class ResultSpec extends Specification with ScalaCheck {
}
}

"sequence for traversables" >> {
"should transform a Seq(Fail) into a Fail" >> prop { xs: Seq[Int] => xs.nonEmpty ==>
(xs.map(Result.fail).sequence must_=== Fail(xs.head))
}
"should transform a Seq(Ok) into an Ok(Seq)" >> prop { xs: Seq[Int] => xs.nonEmpty ==>
(xs.map(Result.ok).sequence must_=== Ok(xs))
"ops on traversables" >> {
"split" >> {
"should split a Seq[Result[E, A]] into a (Seq[E], Seq[A]) " >> prop { xs: Seq[Int] => xs.nonEmpty ==> {
val (fails, oks) = xs.map(x => if (x < 0) Fail(x) else Ok(x)).split
fails must contain(be_<(0)).foreach
oks must contain(be_>=(0)).foreach
}}
"should split an empty Seq into a (Seq.empty, Seq.empty)" >> {
val (fails, oks) = Seq.empty[Result[Int, String]].split
fails must_=== Seq.empty[Int]
oks must_=== Seq.empty[String]
}
}
"should transform an empty Seq into an Ok(Seq.empty)" >> {
Seq.empty[Result[Int, String]].sequence must_=== Ok(Seq.empty[String])
"sequence" >> {
"should transform a Seq(Fail) into a Fail" >> prop { xs: Seq[Int] => xs.nonEmpty ==>
(xs.map(Result.fail).sequence must_=== Fail(xs.head))
}
"should transform a Seq(Ok) into an Ok(Seq)" >> prop { xs: Seq[Int] => xs.nonEmpty ==>
(xs.map(Result.ok).sequence must_=== Ok(xs))
}
"should transform an empty Seq into an Ok(Seq.empty)" >> {
Seq.empty[Result[Int, String]].sequence must_=== Ok(Seq.empty[String])
}
}
}

Expand Down

0 comments on commit c826a13

Please sign in to comment.