nearestOrNull method
Get the closest DateTime to point
in the DateTime array.
If the array is empty, Null is returned.
DateTimeの配列の中でpoint
に一番近いDateTimeを取得します。
配列が空の場合はNullが返されます。
final dateTimeArray = [
DateTime(2022, 12, 20),
DateTime(2022, 12, 28),
DateTime(2023, 1, 12),
];
final nearest = dateTimeArray.nearestOrNull(DateTime(2022, 12, 22)); // DateTime(2022, 12, 20)
Implementation
DateTime? nearestOrNull(DateTime point) {
if (isEmpty) {
return null;
}
DateTime? _res;
int? _point;
final pointMilliseconds = point.millisecondsSinceEpoch;
for (final tmp in this) {
final tmpMilliseconds = tmp.millisecondsSinceEpoch;
if (tmpMilliseconds == pointMilliseconds) {
return tmp;
}
final p = (pointMilliseconds - tmpMilliseconds).abs();
if (_point == null || p < _point) {
_res = tmp;
_point = p;
}
}
return _res;
}