Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
data class Property(val name: String, val objectRef: String? = null)
data class Model(val name: String, val properties: List<Property>)
val m1 = Model(
"m1", listOf(
Property("p11"),
Property("p12", "m2"),
)
)
val m2 = Model(
"m2", listOf(
Property("p21"),
Property("p22", "m3"),
Property("p23", "m3"),
Property("p24", "m5"),
)
)
val m3 = Model(
"m3", listOf(
Property("p31"),
Property("p32", "m4"),
// Property("p33", "m2"),
)
)
val m4 = Model(
"m4", listOf(
Property("p41"),
)
)
val m5 = Model(
"m5", listOf(
Property("p51"),
)
)
val models = listOf(m1, m2, m3, m4, m5)
// -----
fun List<Model>.findRefs(model: Model): List<Model> {
val models = this
fun String.toModel() = models.firstOrNull { it.name == this }
fun Model.children() =
properties.mapNotNull { it.objectRef }.toSet().mapNotNull { modelname -> modelname.toModel() }
// TODO detect cycles
fun Model.collectRefs(acc: List<Model>): List<Model> =
children().flatMap { it.collectRefs(acc) } + this
return model.collectRefs(emptyList())
}
fun main() {
println(models.findRefs(m1).map { it.name })
println(models.findRefs(m2).map { it.name })
println(models.findRefs(m3).map { it.name })
println(models.findRefs(m4).map { it.name })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment