Skip to content

Commit

Permalink
Add modifyRefs method
Browse files Browse the repository at this point in the history
  • Loading branch information
JD557 committed Nov 16, 2023
1 parent d06c23b commit f97e1b7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
10 changes: 10 additions & 0 deletions core/src/main/scala/eu/joaocosta/interim/Ref.scala
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,13 @@ extension [T](x: T) def asRef(block: Ref[T] => Unit): T = Ref.withRef(x)(block)
extension [T <: Product](x: T)
def asRefs(using mirror: Mirror.ProductOf[T])(block: Tuple.Map[mirror.MirroredElemTypes, Ref] => Unit): T =
Ref.withRefs(x)(block)

/** Destructures a Ref into multiple Refs and passes it to a block, returning the updated Ref.
*
* Useful to work with large state objects.
*
* Equivalent to `x.modify(_.asRefs(block))`
*/
extension [T <: Product](x: Ref[T])
def modifyRefs(using mirror: Mirror.ProductOf[T])(block: Tuple.Map[mirror.MirroredElemTypes, Ref] => Unit): Ref[T] =
x.modify(_.asRefs(block))
12 changes: 10 additions & 2 deletions core/src/test/scala/eu/joaocosta/interim/RefSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class RefSpec extends munit.FunSuite:
ref.modify(_ + 2)
assertEquals(result, 2)

test("withRefs allows to build a case class from temporary Ref value"):
test("withRefs allows to build a case class from temporary Ref values"):
case class Foo(x: Int, y: String)
val result = Ref.withRefs(Foo(1, "asd")): (x, y) =>
x := 2
Expand All @@ -39,9 +39,17 @@ class RefSpec extends munit.FunSuite:
ref.modify(_ + 2)
assertEquals(result, 2)

test("asRefs allows to build a case class from temporary Ref value"):
test("asRefs allows to build a case class from temporary Ref values"):
case class Foo(x: Int, y: String)
val result = Foo(1, "asd").asRefs: (x, y) =>
x := 2
y := "dsa"
assertEquals(result, Foo(2, "dsa"))

test("modifyRefs allows to modify a case class Ref from temporary Ref values"):
case class Foo(x: Int, y: String)
val ref = Ref(Foo(1, "asd"))
ref.modifyRefs: (x, y) =>
x := 2
y := "dsa"
assertEquals(ref.get, Foo(2, "dsa"))

0 comments on commit f97e1b7

Please sign in to comment.