nearestOrNull method

int? nearestOrNull(
  1. num point
)

Get the closest int to point in the int array.

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

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

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

final intArray = [
  1, 2, 5, 100
];
final nearest = intArray.nearestOrNull(8); // 5

Implementation

int? nearestOrNull(num point) {
  if (isEmpty || point.isNaN) {
    return null;
  }
  int? res;
  int? tmpPoint;
  for (final tmp in this) {
    if (tmp == point) {
      return tmp;
    }
    final p = (point - tmp).abs().toInt();
    if (tmpPoint == null || p < tmpPoint) {
      res = tmp;
      tmpPoint = p;
    }
  }
  return res;
}