Skip to content

Commit

Permalink
Add forall method to JsResult with Option#forall semantics (#184)
Browse files Browse the repository at this point in the history
  • Loading branch information
aaabramov authored and cchantep committed Sep 25, 2018
1 parent c1a80a5 commit 327bfd6
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ lazy val `play-json` = crossProject(JVMPlatform, JSPlatform).crossType(CrossType
ProblemFilters.exclude[ReversedMissingMethodProblem]("play.api.libs.json.OWrites.contramap"),
ProblemFilters.exclude[ReversedMissingMethodProblem]("play.api.libs.json.JsResult.contains"),
ProblemFilters.exclude[ReversedMissingMethodProblem]("play.api.libs.json.JsResult.exists"),
ProblemFilters.exclude[ReversedMissingMethodProblem]("play.api.libs.json.JsResult.forall"),

// Scala 2.13.0-M4
ProblemFilters.exclude[IncompatibleMethTypeProblem]("play.api.libs.json.LowPriorityDefaultReads.traversableReads"),
Expand Down
10 changes: 10 additions & 0 deletions play-json/shared/src/main/scala/play/api/libs/json/JsResult.scala
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ case class JsSuccess[T](value: T, path: JsPath = JsPath()) extends JsResult[T] {

def exists(p: T => Boolean): Boolean = p(value)

def forall(p: T => Boolean): Boolean = p(value)

def repath(path: JsPath): JsResult[T] = JsSuccess(value, path ++ this.path)

def getOrElse[U >: T](t: => U): U = value
Expand Down Expand Up @@ -71,6 +73,8 @@ case class JsError(errors: collection.Seq[(JsPath, collection.Seq[JsonValidation

def exists(p: Nothing => Boolean): Boolean = false

def forall(p: Nothing => Boolean): Boolean = true

def repath(path: JsPath): JsResult[Nothing] =
JsError(errors.map { case (p, s) => path ++ p -> s })

Expand Down Expand Up @@ -221,6 +225,12 @@ sealed trait JsResult[+A] { self =>
/** If this result is successful than check value with predicate '''p''', otherwise return '''false''' */
def exists(p: A => Boolean): Boolean

/**
* If this result is successful than check value with predicate '''p''', otherwise return '''true'''.
* Follows [[scala.collection.Traversable.forall]] semantics
*/
def forall(p: A => Boolean): Boolean

/** Updates the JSON path */
def repath(path: JsPath): JsResult[A]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,24 @@ class JsResultSpec extends WordSpec with MustMatchers {

}

"JsSuccess#forall" should {

"return true for JsSuccess(x * 2).forall(_ % 2 == 0)" in {
assert(JsSuccess(2).forall(_ % 2 == 0))
}

"return false for JsSuccess(x, {x < 0}).forall(_ >)" in {
assert(!JsSuccess(-1).forall(_ > 0))
}

}

"JsError#forall" should {

"return true" in {
assert(JsError("").forall(_ => false))
}

}

}

0 comments on commit 327bfd6

Please sign in to comment.