YearRange.within constructor
YearRange.within(
- CalendarYear min,
- CalendarYear max,
- int length, {
- CalendarYear? tryToStartAt,
Create a YearRange with desired length and (ideally) start,
constrained by min and max.
The created range will never start before min or end after max. The
length will match length as closely as possible, subject to that
constraint. If possible, the range will start at or close to
tryToStartAt, but this has the lowest priority.
Throws ArgumentError if length is less than 1, min/max are null, or max is before min.
length: int-- Must be at least 1.
Implementation
factory YearRange.within(CalendarYear min, CalendarYear max, int length,
{final CalendarYear? tryToStartAt}) {
if (length < 1) {
throw ArgumentError.value(length, 'length', 'must be at least 1');
}
if (min == null) {
throw ArgumentError.notNull('min');
}
if (max == null) {
throw ArgumentError.notNull('max');
}
int years = min.deltaYears(max) + 1;
if (years < 1) {
throw ArgumentError('max must not be before min');
}
var start = tryToStartAt?.start ?? min.start;
// Clamp to maximum possible length
if (length > years) length = years;
// Enforce minimum
if (start < min.start) {
start = min.start;
}
// Enforce maximum (the end cannot go past max)
var end = start.add(years: length - 1);
if (end > max.start) {
start = max.start.add(years: -(length - 1));
}
return YearRange(start, length);
}