findCommonParent function

Module? findCommonParent(
  1. Module firstChild,
  2. Module secondChild
)

Returns the common parent of two modules firstChild and secondChild. If the two modules are the same, returns that module. If no common parent is found and they are not the same module, returns null.

Implementation

Module? findCommonParent(Module firstChild, Module secondChild) {
  final firstPath = List<Module>.from(firstChild.hierarchy(), growable: false);
  final secondPath =
      List<Module>.from(secondChild.hierarchy(), growable: false);

  if (firstChild.parent == secondChild.parent && firstChild.parent != null) {
    return firstChild.parent;
  }

  if (firstPath[0] != secondPath[0]) {
    // base top parent is not the same, no common parent
    return null;
  }

  if (firstChild == secondChild) {
    // if the two modules are the same, return that module as the common parent
    return firstChild;
  }

  if (secondPath.contains(firstChild) && !firstPath.contains(secondChild)) {
    // firstChild is in the parent hierarchy of second
    return firstChild;
  } else if (!secondPath.contains(firstChild) &&
      firstPath.contains(secondChild)) {
    // secondChild is in the parent hierarchy of first
    return secondChild;
  }

  for (var i = 0; i < firstPath.length; i++) {
    if (firstPath[i] != secondPath[i]) {
      // Assumption there has to be one common parent at the top
      return firstPath[i - 1];
    }
  }

  return null;
}