Skip to content

Nearest-point lookup

Read as Markdown

Locate the nearest observation in pixel and domain space.

Plain source. Run as a browser module after the document body exists. TSX uses jsx: "react-jsx" and jsxImportSource: "@pibbl/core".

import {
nearestDomainValue,
nearestPoint,
type NearestPoint,
type NearestPointOptions,
type ResolvedLinearScale,
} from "@pibbl/core/viz";
const horizontal: ResolvedLinearScale = {
type: "linear",
domain: [0, 10],
range: [0, 300],
frame: { x: 0, y: 0, width: 300, height: 200 },
map: (value) => value * 30,
invert: (pixel) => pixel / 30,
ticks: () => [0, 5, 10],
};
const vertical: ResolvedLinearScale = {
...horizontal,
range: [200, 0],
map: (value) => 200 - value * 20,
invert: (pixel) => (200 - pixel) / 20,
};
const readings = [
{ time: 1, value: 3 },
{ time: 5, value: 7 },
];
const options: NearestPointOptions<(typeof readings)[number]> = {
x: "time",
y: "value",
xScale: horizontal,
yScale: vertical,
maxDistance: 30,
};
const hit: NearestPoint<(typeof readings)[number]> | undefined = nearestPoint(
readings,
{ x: 150, y: 60 },
options,
);
const time = nearestDomainValue(
readings.map((row) => row.time),
140,
horizontal,
);
const output = document.createElement("pre");
output.textContent = `Nearest value: ${hit?.datum.value ?? "none"}\nNearest time: ${time ?? "none"}`;
document.body.append(output);
  • Displays the nearest value and domain coordinate in the document.

Documentation built with @pibbl/core 0.0.2, revision 272a94a. ALPHA — NOT FOR PRODUCTION USE.