validateHierarchy function

HierarchyValidation validateHierarchy(
  1. List<HierarchyUtils> nodes
)

Checks nodes for the problems that make flattenHierarchy throw, and returns them instead of throwing. Runs in O(n).

Ids are matched as described on flattenHierarchy. For an id listed with different parents, the first listed parent is the one used to decide reachability. The cycle, self-parent and descendant lists therefore depend on input order when there are conflicts: reordering the conflicting rows can change them.

Example:

final HierarchyValidation result = validateHierarchy(<HierarchyUtils>[
  const HierarchyUtils('a', 'b'),
  const HierarchyUtils('b', 'a'),
  const HierarchyUtils('c', 'b'),
  const HierarchyUtils('x', 'x'),
]);
result.isValid; // false
result.cycleIds; // ['a', 'b']
result.cycleDescendantIds; // ['c']
result.selfParentIds; // ['x']

Implementation

HierarchyValidation validateHierarchy(List<HierarchyUtils> nodes) {
  final Set<String> conflicts = <String>{};
  final Map<String, String?> parents = HierarchyParent.firstListed(nodes, conflicts);
  return HierarchyValidation._(
    // Filtered from the keys so ids are ordered by first appearance, not by
    // where the conflict happened to be noticed.
    parents.keys.where(conflicts.contains).toList(),
    _classify(parents, _traceAll(parents)),
  );
}