function distanceToNearestItem(point, segments, points, prevBest) {
let nearest = Infinity;
for (let p of points) {
let dx = point[0] - p[0];
let dy = point[1] - p[1];
if (Math.abs(dx) >= nearest || Math.abs(dy) >= nearest) continue;
let d = Math.hypot(dx, dy);
if (d < nearest) {
nearest = d;
if (d <= prevBest) return -1;
}
}
for (let segment of segments) {
if (point[0] >= Math.max(segment[0][0], segment[1][0]) + nearest) continue;
if (point[1] >= Math.max(segment[0][1], segment[1][1]) + nearest) continue;
if (point[0] <= Math.min(segment[0][0], segment[1][0]) - nearest) continue;
if (point[1] <= Math.min(segment[0][1], segment[1][1]) - nearest) continue;
let d = pointToLineDistance(point, segment) * edgeSpacing;
if (d < nearest) {
nearest = d;
if (d <= prevBest) return -1;
}
}
return nearest;
}