TimeRange.centeredAround constructor

TimeRange.centeredAround(
  1. Duration center,
  2. Duration duration, {
  3. bool canShiftIfDoesntFit = true,
})

Implementation

factory TimeRange.centeredAround(
  Duration center,
  Duration duration, {
  bool canShiftIfDoesntFit = true,
}) {
  assert(duration <= 1.days);

  final TimeRange newRange;
  final halfDuration = duration * (1 / 2);
  if (center - halfDuration < 0.days) {
    assert(canShiftIfDoesntFit);
    newRange = TimeRange(0.days, duration);
  } else if (center + halfDuration > 1.days) {
    assert(canShiftIfDoesntFit);
    newRange = TimeRange(1.days - duration, 1.days);
  } else {
    newRange = TimeRange(
      // Ensure that the resulting duration is exactly [duration], even if
      // [halfDuration] was rounded.
      center - duration + halfDuration,
      center + halfDuration,
    );
  }
  assert(newRange.duration == duration);
  return newRange;
}