nearestOrNull method

Clock? nearestOrNull(
  1. DateTime point
)

Get the closest Clock to point in the Clock array.

If the array is empty, Null is returned.

Clockの配列の中でpointに一番近いClockを取得します。

配列が空の場合はNullが返されます。

final clockArray = [
  Clock(2022, 12, 20),
  Clock(2022, 12, 28),
  Clock(2023, 1, 12),
];
final nearest = clockArray.nearestOrNull(Clock(2022, 12, 22)); // Clock(2022, 12, 20)

Implementation

Clock? nearestOrNull(DateTime point) {
  if (isEmpty) {
    return null;
  }
  DateTime? res;
  int? tmpPoint;
  final pointMilliseconds = point.millisecondsSinceEpoch;
  for (final tmp in this) {
    final tmpMilliseconds = tmp.millisecondsSinceEpoch;
    if (tmpMilliseconds == pointMilliseconds) {
      return tmp;
    }
    final p = (pointMilliseconds - tmpMilliseconds).abs();
    if (tmpPoint == null || p < tmpPoint) {
      res = tmp;
      tmpPoint = p;
    }
  }
  if (res == null) {
    return null;
  }
  return Clock.fromDateTime(res);
}