Created
September 6, 2022 15:03
-
-
Save moust/7f6f17cf766a5892f9795812814d8fbc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import shapeless.{HList, LabelledGeneric, Poly1, Witness} | |
import shapeless.labelled.{FieldType, field} | |
import shapeless.ops.hlist | |
import shapeless.tag.@@ | |
trait Primary { | |
val primary: Option[Boolean] | |
} | |
object OnlyOnePrimary { | |
sealed trait LowerPriorityFieldMapper extends Poly1 { | |
implicit def c[K, V]: Case.Aux[FieldType[K, V], FieldType[K, V]] = | |
at[FieldType[K, V]](identity) | |
} | |
object unflagPrimary extends LowerPriorityFieldMapper { | |
type PrimaryKey = Symbol @@ Witness.`"primary"`.T | |
implicit val primary: Case.Aux[FieldType[PrimaryKey, Option[Boolean]], FieldType[PrimaryKey, Option[Boolean]]] = | |
at[FieldType[PrimaryKey, Option[Boolean]]] { _ => | |
field[PrimaryKey](Some(false)) | |
} | |
} | |
def apply[A <: Primary, Repr <: HList]( | |
list: List[A] | |
)(implicit generic: LabelledGeneric.Aux[A, Repr], | |
mapper: hlist.Mapper.Aux[unflagPrimary.type, Repr, Repr], | |
): List[A] = | |
list match { | |
case Nil => Nil | |
case head :: tail if head.primary.exists(identity) => | |
head :: tail.map { elem => | |
generic.from(generic.to(elem).map(unflagPrimary)) | |
} | |
case head :: tail => head :: apply(tail) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment