Skip to content

Commit

Permalink
Merge pull request #759 from adzerk/make-fromFullPaths-tail-recursive
Browse files Browse the repository at this point in the history
Make fromFullPaths tail recursive
  • Loading branch information
jcazevedo authored Nov 21, 2024
2 parents dea8a72 + d177737 commit 16599f9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
15 changes: 11 additions & 4 deletions circe/src/main/scala/com/kevel/apso/circe/Implicits.scala
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.kevel.apso.circe

import scala.annotation.tailrec
import scala.util.Try

import io.circe._
Expand Down Expand Up @@ -121,11 +122,17 @@ object Implicits {
}
}

paths match {
case Nil => Json.obj()
case (path, value) :: rem =>
createJson(path.split(separatorRegex).toList, value).deepMerge(fromFullPaths(rem, separatorRegex))
@tailrec
def fromFullPathsRec(paths: Seq[(String, Json)], acc: Json): Json = {
paths match {
case Nil => acc
case (path, value) :: rem =>
val newAcc = acc.deepMerge(createJson(path.split(separatorRegex).toList, value))
fromFullPathsRec(rem, newAcc)
}
}

fromFullPathsRec(paths, Json.obj())
}

final implicit class ApsoJsonEncoder[A](val encoder: Encoder[A]) extends AnyVal {
Expand Down
13 changes: 13 additions & 0 deletions circe/src/test/scala/com/kevel/apso/circe/ImplicitsSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,19 @@ class ImplicitsSpec extends Specification {

res mustEqual expectedJson
}

"not throw a StackOverflowError for large lists of paths" in {
val paths = (1 to 10000).map(i => (s"a.v$i", i.asJson)).toList
fromFullPaths(paths, ".") must not(throwAn[StackOverflowError])
}

"giving precedence to the last path value if duplicate paths exist" in {
val json1 = fromFullPaths(List("a" -> 1.asJson, "a" -> 2.asJson, "a" -> 3.asJson))
json1 mustEqual json"""{"a": 3}"""

val json2 = fromFullPaths(List("a.b.c" -> 1.asJson, "a.b" -> 2.asJson, "a" -> 3.asJson))
json2 mustEqual json"""{"a": 3}"""
}
}

"provide a method to get the key set of a JSON Object" in {
Expand Down

0 comments on commit 16599f9

Please sign in to comment.