treeToString<Node extends TreeNode<Object>> function

String treeToString<Node extends TreeNode<Object>>(
  1. Node root, [
  2. String describeNode(
    1. Node
    )?
])

Converts an tree to an textual representation in a manner similar to the tree command.

Implementation

String treeToString<Node extends TreeNode<Object>>(
  Node root, [
  String Function(Node)? describeNode,
]) {
  ArgumentError.checkNotNull(root);
  final buff = StringBuffer()
    ..writeln(describeNode?.call(root) ?? root.value.toString());

  final children = root.edges.toList();
  for (var i = 0; i < children.length; i++) {
    final child = children[i];
    final childStr = treeToString<Node>(child as Node, describeNode).trim();
    final childLns = childStr.split('\n');
    final isLast = i + 1 == children.length;

    if (isLast) {
      var isFirst = true;
      for (final ln in childLns) {
        buff.writeln('${isFirst ? _lastConnector : _indent}$ln');
        isFirst = false;
      }
    } else {
      var isFirst = true;
      for (final ln in childLns) {
        buff.writeln('${isFirst ? _connector : _continuation}$ln');
        isFirst = false;
      }
    }
  }

  return buff.toString();
}