Thanks to visit codestin.com
Credit goes to github.com

Skip to content
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
34 changes: 34 additions & 0 deletions core-tests/shared/src/test/scala/zio/ZIOSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1434,6 +1434,40 @@ object ZIOSpec
""".stripMargin
}
}
),
suite("doWhile")(
testM("doWhile repeats while condition is true") {
for {
in <- Ref.make(10)
out <- Ref.make(0)
_ <- (in.update(_ - 1) <* out.update(_ + 1)).doWhile(_ >= 0)
result <- out.get
} yield assert(result, equalTo(11))
},
testM("doWhile always evaluates effect once") {
for {
ref <- Ref.make(0)
_ <- ref.update(_ + 1).doWhile(_ => false)
result <- ref.get
} yield assert(result, equalTo(1))
}
),
suite("doUntil")(
testM("doUntil repeats until condition is true") {
for {
in <- Ref.make(10)
out <- Ref.make(0)
_ <- (in.update(_ - 1) <* out.update(_ + 1)).doUntil(_ == 0)
result <- out.get
} yield assert(result, equalTo(10))
},
testM("doUntil always evaluates effect once") {
for {
ref <- Ref.make(0)
_ <- ref.update(_ + 1).doUntil(_ => true)
result <- ref.get
} yield assert(result, equalTo(1))
}
)
)
)
Expand Down
12 changes: 12 additions & 0 deletions core/shared/src/main/scala/zio/ZIO.scala
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,18 @@ sealed trait ZIO[-R, +E, +A] extends Serializable { self =>
final def delay(duration: Duration): ZIO[R with Clock, E, A] =
clock.sleep(duration) *> self

/**
* Repeats this effect until its result satisfies the specified predicate.
*/
final def doUntil(f: A => Boolean): ZIO[R, E, A] =
repeat(Schedule.doUntil(f))

/**
* Repeats this effect while its result satisfies the specified predicate.
*/
final def doWhile(f: A => Boolean): ZIO[R, E, A] =
repeat(Schedule.doWhile(f))

/**
* Returns an effect whose failure and success have been lifted into an
* `Either`.The resulting effect cannot fail, because the failure case has
Expand Down
4 changes: 2 additions & 2 deletions test/shared/src/main/scala/zio/test/Gen.scala
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ package zio.test

import scala.collection.immutable.SortedMap

import zio.{ Schedule, UIO, ZIO }
import zio.{ UIO, ZIO }
import zio.random._
import zio.stream.{ Stream, ZStream }

Expand Down Expand Up @@ -290,7 +290,7 @@ object Gen extends GenZIO with FunctionVariants {
val difference = max - min + 1
val effect =
if (difference > 0) nextLong(difference).map(min + _)
else nextLong.repeat(Schedule.doUntil(n => min <= n && n <= max))
else nextLong.doUntil(n => min <= n && n <= max)
effect.map(Sample.shrinkIntegral(min))
}

Expand Down