mergeOverlappingPeriods static method

List<Period> mergeOverlappingPeriods(
  1. List<Period> periods, {
  2. bool sort = true,
})

Returns a list of periods that are the union of the given periods.

The periods will be sorted if sort is true.

It will iterate over the periods and merge the periods that overlap. If the periods do not overlap, they are added to the list as is. If the periods overlap, the union of the periods will be added to the list.

Implementation

static List<Period> mergeOverlappingPeriods(
  List<Period> periods, {
  bool sort = true,
}) {
  final localPeriods = [...periods];
  if (sort) localPeriods.sort();
  return localPeriods.fold<List<Period>>([], (merged, current) {
    if (merged.isEmpty) {
      merged.add(current);
    } else {
      final last = merged.last;
      if (last.overlapsWith(current)) {
        merged
          ..removeLast()
          ..add(last.mergeWith(current)!);
      } else {
        merged.add(current);
      }
    }
    return merged;
  });
}