nearestOrNull method
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を取得します。
配列が空の場合やpoint
がdouble.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? tmpPoint;
for (final tmp in this) {
if (tmp == point) {
return tmp;
}
final p = (point - tmp).abs();
if (tmpPoint == null || p < tmpPoint) {
res = tmp;
tmpPoint = p;
}
}
return res;
}