treeToGraph<T, Node extends GraphNode<T>> function

Graph<T, Node> treeToGraph<T, Node extends GraphNode<T>>(
  1. TreeNode<T> root,
  2. Node createNode(
    1. T value
    ), {
  3. TreeToGraphLinkType linkType = TreeToGraphLinkType.direct,
})

Convert an tree, which may have more than one TreeNode representing the same value into an Graph, which may be interlinked or not.

Implementation

Graph<T, Node> treeToGraph<T, Node extends GraphNode<T>>(
  TreeNode<T> root,
  Node Function(T value) createNode, {
  TreeToGraphLinkType linkType = TreeToGraphLinkType.direct,
}) {
  final valueNodeMap = <T, Node>{
    root.value: createNode(root.value),
  };
  final it = walkTree<T, void>(root, (value, parent) {
    final currNode = valueNodeMap.putIfAbsent(value, () => createNode(value));
    final parNode = parent.fmap((parentVal) => valueNodeMap.putIfAbsent(
          parentVal,
          () => createNode(parentVal),
        ));
    parNode.visit<void>(
        just: (parent) {
          switch (linkType) {
            case TreeToGraphLinkType.direct:
              parent.addEdge(currNode);
              break;
            case TreeToGraphLinkType.reverse:
              currNode.addEdge(parent);
              break;
            case TreeToGraphLinkType.interlinked:
              parent.addEdge(currNode);
              currNode.addEdge(parent);
              break;
          }
        },
        none: nothing);
  }).iterator;

  while (it.moveNext()) {}

  if (linkType == TreeToGraphLinkType.reverse) {
    return NodesGraph(valueNodeMap.values.toList());
  }
  return RootGraph(valueNodeMap[root.value]!);
}