Skip to content

Commit

Permalink
ToJson instances for Either (#48)
Browse files Browse the repository at this point in the history
  • Loading branch information
nrktkt authored Dec 14, 2022
1 parent 50ecd31 commit 88868c7
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
7 changes: 6 additions & 1 deletion ninny/src/nrktkt/ninny/ToJsonInstances.scala
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,14 @@ trait ToJsonInstances

implicit val noneToJson: ToJson[None.type] = _ => None
implicit def someToJson[A: ToJson]: ToJson[Some[A]] = optionToJson[A].to(_)
implicit def someToSomeJson[A: ToSomeJson]: ToSomeJson[Some[A]] =
implicit def someToSomeJson[A: ToSomeJson]: ToSomeJson[Some[A]] =
_.value.toSomeJson

implicit def leftToJson[L: ToJson, R]: ToJson[Left[L, R]] = _.value.toJson
implicit def rightToJson[L, R: ToJson]: ToJson[Right[L, R]] = _.value.toJson
implicit def eitherToJson[L: ToJson, R: ToJson]: ToJson[Either[L, R]] =
_.fold(_.toJson, _.toJson)

implicit val instantToJson: ToSomeJson[Instant] =
i => JsonNumber(i.getEpochSecond.toDouble)

Expand Down
25 changes: 25 additions & 0 deletions ninny/test/src/nrktkt/ninny/ToJsonInstancesSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package nrktkt.ninny

import org.scalatest._
import org.scalatest.flatspec._
import org.scalatest.matchers._
import io.github.kag0.ninny.ast._

class ToJsonInstancesSpec extends AnyFlatSpec with should.Matchers {
"Either values" should
"convert right to json" in {
val right = Right[Int, String]("test")
val either: Either[Int, String] = right
val expected = Some(JsonString("test"))
right.toJson shouldEqual expected
either.toJson shouldEqual expected
}

it should "convert left to json" in {
val left = Left[Int, String](5)
val either: Either[Int, String] = left
val expected = Some(JsonNumber(5))
left.toJson shouldEqual expected
either.toJson shouldEqual expected
}
}

0 comments on commit 88868c7

Please sign in to comment.