Have sampleSome do a maximum of 10 attempts

This commit is contained in:
Torkel Rogstad 2019-07-01 19:02:01 +02:00
parent d8e214bbbf
commit af6c880a24

View file

@ -13,11 +13,22 @@ object Implicits {
/** Extension methods for Scalacheck generatos */
implicit class GeneratorOps[T](private val gen: Gen[T]) extends AnyVal {
@tailrec
/** Gets a sample from this generator that's not `None` */
def sampleSome: T = gen.sample match {
case None => sampleSome
case Some(sample) => sample
def sampleSome: T = {
val max = 10
@tailrec
def loop(counter: Int): T =
if (counter > max) {
sys.error(
s"Could not get a sample from generator after $max attempts")
} else {
gen.sample match {
case None => loop(counter + 1)
case Some(sample) => sample
}
}
loop(0)
}
}
}