From fcd5268ed350ee2ed798e8c76832cd372e47a77f Mon Sep 17 00:00:00 2001 From: Timo Meijer Date: Mon, 28 Feb 2022 19:38:08 +0100 Subject: [PATCH] Add validated and validatedNec to boolean (#319) --- shared/src/main/scala/mouse/boolean.scala | 8 +++++++- shared/src/test/scala/mouse/BooleanSyntaxTest.scala | 10 ++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/shared/src/main/scala/mouse/boolean.scala b/shared/src/main/scala/mouse/boolean.scala index bf37ed11..ebaab969 100644 --- a/shared/src/main/scala/mouse/boolean.scala +++ b/shared/src/main/scala/mouse/boolean.scala @@ -1,6 +1,6 @@ package mouse -import cats.data.{EitherNel, NonEmptyList, Validated, ValidatedNel} +import cats.data.{EitherNel, NonEmptyList, Validated, ValidatedNec, ValidatedNel} import cats.{Applicative, ApplicativeError, Monoid} import mouse.BooleanSyntax.LiftToPartiallyApplied @@ -23,6 +23,12 @@ final class BooleanOps(private val b: Boolean) extends AnyVal { @inline def eitherNel[L, R](ifFalse: => L, ifTrue: => R): EitherNel[L, R] = either(NonEmptyList.one(ifFalse), ifTrue) + @inline def validated[L, R](ifFalse: => L, ifTrue: => R): Validated[L, R] = + fold(Validated.valid(ifTrue), Validated.invalid(ifFalse)) + + @inline def validatedNec[L, R](ifFalse: => L, ifTrue: => R): ValidatedNec[L, R] = + fold(Validated.validNec(ifTrue), Validated.invalidNec(ifFalse)) + @inline def validatedNel[L, R](ifFalse: => L, ifTrue: => R): ValidatedNel[L, R] = fold(Validated.validNel(ifTrue), Validated.invalidNel(ifFalse)) diff --git a/shared/src/test/scala/mouse/BooleanSyntaxTest.scala b/shared/src/test/scala/mouse/BooleanSyntaxTest.scala index 77e1181b..95dcbaa2 100644 --- a/shared/src/test/scala/mouse/BooleanSyntaxTest.scala +++ b/shared/src/test/scala/mouse/BooleanSyntaxTest.scala @@ -19,6 +19,16 @@ class BooleanSyntaxTest extends MouseSuite { assertEquals(false.eitherNel("error", 1), Either.left(NonEmptyList.one("error"))) } + test("BooleanSyntax.validated") { + assertEquals(true.validated("error", 1), Validated.valid(1)) + assertEquals(false.validated("error", 1), Validated.invalid("error")) + } + + test("BooleanSyntax.validatedNec") { + assertEquals(true.validatedNec("error", 1), Validated.validNec(1)) + assertEquals(false.validatedNec("error", 1), Validated.invalidNec("error")) + } + test("BooleanSyntax.validatedNel") { assertEquals(true.validatedNel("error", 1), Validated.validNel(1)) assertEquals(false.validatedNel("error", 1), Validated.invalidNel("error"))