transform<U extends PgnNodeData, C> method

PgnNode<U> transform<U extends PgnNodeData, C>(
  1. C context,
  2. (C, U)? f(
    1. C context,
    2. T data,
    3. int childIndex
    )
)

Transform this node into a PgnNode<U> tree.

The callback function f is called for each node in the tree. If the callback returns null, the node is not added to the result tree. The callback should return a tuple of the updated context and node data.

Implementation

PgnNode<U> transform<U extends PgnNodeData, C>(
    C context, (C, U)? Function(C context, T data, int childIndex) f) {
  final root = PgnNode<U>();
  final stack = [(before: this, after: root, context: context)];

  while (stack.isNotEmpty) {
    final frame = stack.removeLast();
    for (int childIdx = 0;
        childIdx < frame.before.children.length;
        childIdx++) {
      C ctx = frame.context;
      final childBefore = frame.before.children[childIdx];
      final transformData = f(ctx, childBefore.data, childIdx);
      if (transformData != null) {
        final (newCtx, data) = transformData;
        ctx = newCtx;
        final childAfter = PgnChildNode(data);
        frame.after.children.add(childAfter);
        stack.add((before: childBefore, after: childAfter, context: ctx));
      }
    }
  }
  return root;
}