Skip to content

Commit

Permalink
Add default instances for NonEmptyList
Browse files Browse the repository at this point in the history
  • Loading branch information
lowmelvin committed Aug 25, 2023
1 parent 7d05b9c commit 73706ae
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 2 deletions.
6 changes: 6 additions & 0 deletions src/main/scala/com/melvinlow/formify/instances.scala
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,12 @@ object instances {
encoded.zipWithIndex.map { case (value, idx) => (idx.toString, value) }.toMap
}

given neListFormEncoder_F[T: FormDataEncoder]: FormDataEncoder[NonEmptyList[T]] =
FormDataEncoder[List[T]].contramap(_.toList)

given neListFormEncoder_V[T: FormValueEncoder]: FormDataEncoder[NonEmptyList[T]] =
FormDataEncoder[List[T]].contramap(_.toList)

given neChainFormEncoder_F[T: FormDataEncoder]: FormDataEncoder[NonEmptyChain[T]] =
FormDataEncoder[List[T]].contramap(_.toList)

Expand Down
35 changes: 35 additions & 0 deletions src/test/scala/com/melvinlow/formify/FormDataEncoderSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -511,4 +511,39 @@ object FormDataEncoderSpec extends weaver.FunSuite {
)
}
}

test("should encode a NonEmptyList[Int]") {
import com.melvinlow.formify.instances.auto.given

val instance = NonEmptyList(1, List(2, 3))
val encoded = FormDataEncoder[NonEmptyList[Int]].encode(instance)

given FormFieldComposer = FormFieldComposer.make(_.toList.mkString("."))

expect {
encoded.compile == Chain(
("0", "1"),
("1", "2"),
("2", "3")
)
}
}

test("should encode a NonEmptyList[List[Int]]") {
import com.melvinlow.formify.instances.auto.given

val instance = NonEmptyList(List(1, 2), List(List(3, 4)))
val encoded = FormDataEncoder[NonEmptyList[List[Int]]].encode(instance)

given FormFieldComposer = FormFieldComposer.make(_.toList.mkString("."))

expect {
encoded.compile == Chain(
("0.0", "1"),
("0.1", "2"),
("1.0", "3"),
("1.1", "4")
)
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.melvinlow.formify

object FormFieldFragmentSpec$ extends weaver.FunSuite {
object FormFieldFragmentSpec extends weaver.FunSuite {
test("should wrap and unwrap") {
expect(FormFieldFragment("hello").underlying == "hello")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package com.melvinlow.formify
import cats.data.*
import cats.syntax.all.*

object FormFieldSpec$ extends weaver.FunSuite {
object FormFieldSpec extends weaver.FunSuite {
test("should wrap and unwrap") {
val fragment = FormFieldFragment("hello")
expect(FormField.one(fragment).underlying == NonEmptyChain(fragment))
Expand Down

0 comments on commit 73706ae

Please sign in to comment.