All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.toxicbakery.kfinstatemachine.graph.DirectedGraph.kt Maven / Gradle / Ivy

The newest version!
package com.toxicbakery.kfinstatemachine.graph

/**
 * Graph implementation built by defining nodes via their associated edges.
 * The graph may contain one or groups of edges.
 *
 * @param mappedEdges edges of the graph grouped by their left node pointing to `n` nodes
 */
open class DirectedGraph(
        private val mappedEdges: List>>
) : IDirectedGraph {

    override val nodes: Set = mappedEdges
            .flatMap {
                mappedEdges.flatMap { (_, edgeMap) ->
                    edgeMap.values
                }
            }
            .plus(mappedEdges.map { (node, _) -> node })
            .toSet()

    override fun transitions(node: N): Set =
            edges(node).keys

    override fun edges(
            node: N,
            defaultValue: () -> Map
    ): Map = mappedEdges
            .filter { (n, _) -> n == node }
            .flatMap { (_, edge) -> edge.entries.map { entry -> entry.key to entry.value } }
            .toMap()
            .let { map -> if (map.isEmpty()) defaultValue() else map }

    /**
     * Source graph defining this graph instance.
     */
    fun graph(): List>> = mappedEdges

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy