intersections static method
Returns a list of periods that are the intersection of the given periods.
The periods will be sorted if sort
is true
.
It will iterate over the periods and get the intersections of the periods.
If the periods do not overlap, they are added to the list as is. If the periods overlap, the intersection of the periods will be added to the list.
Implementation
static List<Period> intersections(List<Period> periods, {bool sort = true}) {
final localPeriods = [...periods];
if (sort) localPeriods.sort();
if (localPeriods.isEmpty) return [];
final merged = <Period>[localPeriods.first];
for (var i = 1; i < localPeriods.length; i++) {
final current = localPeriods[i];
final previous = localPeriods[i - 1];
final lastMerged = merged.last;
if (lastMerged.overlapsWith(current)) {
merged
..removeLast()
..add(lastMerged.getIntersection(current)!);
} else if (previous.overlapsWith(current)) {
merged.add(previous.getIntersection(current)!);
} else {
merged.add(current);
}
}
return merged;
}