# geom

n-dimensional geometry utilities: centroid, dot product, magnitude, normalisation, point-on-segment projection, and point-to-segment distance.

All functions are dimension-agnostic unless otherwise noted — pass `dim` to specify the number of coordinates to use.

---

## Types

```typescript
type Point   = number[];
type Vector  = number[];
type Segment = [Point, Point];
```

---

## centroid

```typescript
function centroid(points: Point[], dim: number): Point
```

Returns the arithmetic mean of the given points in `dim` dimensions.

Throws `RangeError` when `points` is empty.

```typescript
centroid([[0,0],[3,0],[0,3]], 2);  // [1, 1]
centroid([], 2);                   // throws RangeError
```

---

## dot

```typescript
function dot(vec1: Vector, vec2: Vector, dim: number): number
```

Dot product of two vectors, considering only the first `dim` components.

```typescript
dot([1, 0], [0, 1], 2);     // 0  (orthogonal)
dot([1, 2, 3], [4, 5, 6], 3); // 32
```

---

## magnitude

```typescript
function magnitude(vec: Vector): number
```

Euclidean length of `vec` (all components used).

```typescript
magnitude([3, 4]);    // 5
magnitude([0, 0]);    // 0
```

---

## normalize

```typescript
function normalize(vec: Vector): Vector
```

Returns a unit vector in the same direction as `vec`.

Throws `RangeError` when `vec` is the zero vector.

```typescript
normalize([3, 4]);  // [0.6, 0.8]
normalize([0, 0]);  // throws RangeError
```

---

## projectPointOnSegment

```typescript
function projectPointOnSegment(point: Point, seg: Segment, dim: number): Point
```

Returns the orthogonal projection of `point` onto the **infinite line** defined by `seg` (not clamped to the segment endpoints). Result has `dim` components.

```typescript
projectPointOnSegment([2, 3], [[0,0],[4,0]], 2);         // [2, 0]
projectPointOnSegment([2, 3, 5], [[0,0,0],[4,0,0]], 3);  // [2, 0, 0]
```

---

## pointSegmentDistance

```typescript
function pointSegmentDistance(point: Point, seg: Segment, dim: number): number
```

Returns the minimum distance from `point` to the **finite segment** `seg`.

- If the perpendicular projection lies within the segment, returns the perpendicular distance.
- Otherwise returns the distance to the nearer endpoint.

```typescript
pointSegmentDistance([2, 3], [[0,0],[4,0]], 2);   // 3
pointSegmentDistance([-1, 0], [[0,0],[4,0]], 2);  // 1
```
