24 lines
580 B
TypeScript
24 lines
580 B
TypeScript
import type { Vec } from "./given.ts";
|
|
|
|
/** The length (magnitude) of the arrow. */
|
|
export function length(a: Vec): number {
|
|
return Math.sqrt(a.x * a.x + a.y * a.y);
|
|
}
|
|
|
|
/**
|
|
* A unit-length vector pointing the same way as `a`.
|
|
* MUST return (0, 0) when `a` is the zero vector — do not divide by zero.
|
|
*/
|
|
export function normalize(a: Vec): Vec {
|
|
const len = length(a);
|
|
const x = a.x === 0 ? 0 : a.x / len;
|
|
const y = a.y === 0 ? 0 : a.y / len;
|
|
|
|
return { x, y };
|
|
}
|
|
|
|
/** The dot product a·b. */
|
|
export function dot(a: Vec, b: Vec): number {
|
|
return a.x * b.x + a.y * b.y;
|
|
}
|