Add variance to coordinate utils

This commit is contained in:
2024-12-14 17:13:15 +01:00
parent 85b7336a54
commit f1cbb03deb
+28
View File
@@ -1,3 +1,5 @@
import { sumBy } from './array.ts';
export const Sides = { export const Sides = {
TOP: 0, TOP: 0,
RIGHT: 1, RIGHT: 1,
@@ -7,6 +9,15 @@ export const Sides = {
export type Side = (typeof Sides)[keyof typeof Sides]; export type Side = (typeof Sides)[keyof typeof Sides];
export const CoordinateIndices = {
x: 0,
y: 1,
side: 2
} as const;
export type CoordinateIndex =
(typeof CoordinateIndices)[keyof typeof CoordinateIndices];
export type Coordinate = [number, number]; export type Coordinate = [number, number];
export type CoordinateSide = [number, number, Side]; export type CoordinateSide = [number, number, Side];
export type Coordinates = Coordinate[]; export type Coordinates = Coordinate[];
@@ -139,3 +150,20 @@ export function getNeighbouringSides(
return { before, after, neighbours }; return { before, after, neighbours };
} }
/**
* Calculate the variance (difference from the average) of one dimension from coordinates.
* @param coords Array of Coordinates
* @param index `CoordinateIndices.x` for x, `CoordinateIndices.y` for y, `CoordinateIndices.side` for side
*/
export function calculateVariance<C extends Coordinate | CoordinateSide>(
coords: C[],
index: C extends Coordinate ? 0 | 1 : CoordinateIndex
) {
const mean =
sumBy(coords as CoordinateSides, (c) => c[index]) / coords.length;
return (
sumBy(coords as CoordinateSides, (c) => Math.pow(c[index] - mean, 2)) /
coords.length
);
}