DateParts.of constructor
Implementation
factory DateParts.of(List<DatePart> parts) {
final copy = {...parts.asMap()};
int? monthIndex, yearIndex, dayIndex;
int? month, year, day;
parts.forEachIndexed((item, index) {
if (item.period == Period.month) {
monthIndex = index;
month = item.value;
} else if (item.value > 1000) {
yearIndex = index;
year = item.value;
}
});
copy.remove(monthIndex);
copy.remove(yearIndex);
yearIndex = monthIndex = null;
/// Second pass
copy.values.forEachIndexed((item, index) {
if (year != null && item.value > 12 && item.value <= 31) {
/// We already have a year, so any value larger than 12 must be the day
day = item.value;
dayIndex = index;
} else if (year == null && item.value > 31) {
/// Any value larger than 31 must be a year
year = item.value;
yearIndex = index;
}
});
copy.remove(dayIndex);
copy.remove(yearIndex);
dayIndex = yearIndex = monthIndex = null;
List<int> toRemove = [];
List<int> invalidValues = [];
/// Last pass
copy.values.forEachIndexed((item, index) {
if (year != null && day != null && month == null && item.value < 12) {
month = item.value;
monthIndex = index;
} else if (month != null && day != null && year == null) {
year = item.value;
yearIndex = index;
} else if (month != null && year != null && item.value <= 31) {
day = item.value;
dayIndex = index;
} else if (year != null && item.value > 31) {
toRemove.add(index);
invalidValues.add(item.value);
}
});
copy.remove(dayIndex);
copy.remove(yearIndex);
copy.remove(monthIndex);
toRemove.forEach(copy.remove);
return DateParts(
year,
month,
day,
copy.values.map((v) => v.value).toList(),
invalidValues,
);
}