Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make fromFullPaths tail recursive #759

Merged
merged 5 commits into from
Nov 21, 2024
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
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