Skip to content

Commit

Permalink
prefixed uuid ideas
Browse files Browse the repository at this point in the history
  • Loading branch information
djnzx committed Sep 8, 2023
1 parent 338e7ab commit 26b41a6
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
3 changes: 2 additions & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,8 @@ lazy val ce3 = (project in file("ce3"))
"org.typelevel" %% "cats-effect" % "3.5.1",
"org.typelevel" %% "cats-parse" % "0.3.10",
"com.github.cb372" %% "cats-retry" % "3.1.0",
"co.fs2" %% "fs2-core" % "3.8.0",
"co.fs2" %% "fs2-core" % "3.9.1",
"co.fs2" %% "fs2-reactive-streams" % "3.9.1",
"co.fs2" %% "fs2-io" % "3.8.0",
"com.github.fd4s" %% "fs2-kafka" % "2.6.1",
"org.typelevel" %% "munit-cats-effect-3" % "1.0.7",
Expand Down
42 changes: 42 additions & 0 deletions ce3/src/main/scala/_newage/PrefixedUuidPlayground2.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package _newage

import cats.implicits._

import java.util.UUID
import scala.util.Try
import cats.Show

object PrefixedUuidPlayground2 extends App {

private trait IdExtractor[A] extends (A => String)

abstract class IdBase[A](private val prefix: String, private val idFn: IdExtractor[A]) {
implicit val show: Show[A] = (a: A) => s"$prefix${idFn(a)}"

def unapply(raw: String): Option[UUID] =
Option(raw)
.collect { case s if s.startsWith(prefix) => s.substring(prefix.length) }
.flatMap(s => Try(UUID.fromString(s)).toOption)

def is(raw: String): Boolean = unapply(raw).fold(false)(_ => true)
}

case class CarId(id: UUID) extends AnyVal
object CarId extends IdBase[CarId]("CAR-", _.id.toString)

// usecase
val s = CarId(UUID.randomUUID()).show
println(s)

// matching
def check(raw: String): Either[String, UUID] = raw match {
case CarId(id) => id.asRight
case _ => "not a car id".asLeft
}

Seq(
s,
"whatever"
).map(x => check(x) -> CarId.is(x))
.foreach(println)
}

0 comments on commit 26b41a6

Please sign in to comment.