findCommonParent function
Returns the common parent of two modules firstChild
and secondChild
Assuming at least one common parent exists
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 (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;
}