import { Point2D } from './types'; /** * Returns a closure which determines whether points fall within a 2D polygon. * @param selection vertices of the polygon to use to classify points. */ export function pointInPolygon(polygon: Point2D[]): (point: Point2D) => boolean { return (point: Point2D): boolean => { const x = point.x, y = point.y; let inside = false; for (let i: number = 0; i < polygon.length; ++i) { const j = i === 0 ? polygon.length - 1 : i - 1; const xi = polygon[i].x, yi = polygon[i].y, xj = polygon[j].x, yj = polygon[j].y; if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside; } return inside; }; }