First implementation of element distance functions with failing tests

This commit is contained in:
Mark Tolmacs 2024-09-25 18:30:53 +02:00
parent 47cc842415
commit d9ea7190ec
No known key found for this signature in database
6 changed files with 275 additions and 173 deletions

View file

@ -1,6 +1,6 @@
import { pointsEqual } from "./point";
import { segment, segmentIncludesPoint } from "./segment";
import type { GenericPoint, Polygon } from "./types";
import { segment, segmentIncludesPoint, segmentsIntersectAt } from "./segment";
import type { GenericPoint, Polygon, Segment } from "./types";
import { PRECISION } from "./utils";
export function polygon<Point extends GenericPoint>(...points: Point[]) {
@ -62,3 +62,25 @@ function polygonClose<Point extends GenericPoint>(polygon: Point[]) {
function polygonIsClosed<Point extends GenericPoint>(polygon: Point[]) {
return pointsEqual(polygon[0], polygon[polygon.length - 1]);
}
/**
* Returns the points of intersection of a line segment, identified by exactly
* one start pointand one end point, and the polygon identified by a set of
* ponits representing a set of connected lines.
*/
export function polygonSegmentIntersectionPoints<Point extends GenericPoint>(
polygon: Readonly<Polygon<Point>>,
segment: Readonly<Segment<Point>>,
): Point[] {
return polygon
.reduce((segments, current, idx, poly) => {
return idx === 0
? []
: ([
...segments,
[poly[idx - 1] as Point, current],
] as Segment<Point>[]);
}, [] as Segment<Point>[])
.map((s) => segmentsIntersectAt(s, segment))
.filter((point) => point !== null) as Point[];
}