nearestOrNull method

double? nearestOrNull(
  1. num point
)

Get the closest double to point in the double array.

Null is returned if the array is empty or if point is double.nan.

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

配列が空の場合やpointdouble.nanの場合はNullが返されます。

final doubleArray = [
  1.0, 2.0, 5.0, 100.0
];
final nearest = doubleArray.nearestOrNull(8.0); // 5.0

Implementation

double? nearestOrNull(num point) {
  if (isEmpty || point.isNaN) {
    return null;
  }
  double? _res;
  double? _point;
  for (final tmp in this) {
    if (tmp == point) {
      return tmp;
    }
    final p = (point - tmp).abs();
    if (_point == null || p < _point) {
      _res = tmp;
      _point = p;
    }
  }
  return _res;
}