You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.5 KiB
TypeScript
56 lines
1.5 KiB
TypeScript
5 years ago
|
import { Point } from "./types";
|
||
|
|
||
5 years ago
|
export const getSizeFromPoints = (points: readonly Point[]) => {
|
||
5 years ago
|
const xs = points.map((point) => point[0]);
|
||
|
const ys = points.map((point) => point[1]);
|
||
5 years ago
|
return {
|
||
|
width: Math.max(...xs) - Math.min(...xs),
|
||
|
height: Math.max(...ys) - Math.min(...ys),
|
||
|
};
|
||
5 years ago
|
};
|
||
4 years ago
|
|
||
3 years ago
|
/** @arg dimension, 0 for rescaling only x, 1 for y */
|
||
5 years ago
|
export const rescalePoints = (
|
||
5 years ago
|
dimension: 0 | 1,
|
||
3 years ago
|
newSize: number,
|
||
|
points: readonly Point[],
|
||
3 years ago
|
normalize: boolean,
|
||
5 years ago
|
): Point[] => {
|
||
3 years ago
|
const coordinates = points.map((point) => point[dimension]);
|
||
|
const maxCoordinate = Math.max(...coordinates);
|
||
|
const minCoordinate = Math.min(...coordinates);
|
||
|
const size = maxCoordinate - minCoordinate;
|
||
|
const scale = size === 0 ? 1 : newSize / size;
|
||
|
|
||
3 years ago
|
let nextMinCoordinate = Infinity;
|
||
|
|
||
|
const scaledPoints = points.map((point): Point => {
|
||
3 years ago
|
const newCoordinate = point[dimension] * scale;
|
||
|
const newPoint = [...point];
|
||
|
newPoint[dimension] = newCoordinate;
|
||
3 years ago
|
if (newCoordinate < nextMinCoordinate) {
|
||
|
nextMinCoordinate = newCoordinate;
|
||
|
}
|
||
3 years ago
|
return newPoint as unknown as Point;
|
||
|
});
|
||
3 years ago
|
|
||
|
if (!normalize) {
|
||
|
return scaledPoints;
|
||
|
}
|
||
|
|
||
|
if (scaledPoints.length === 2) {
|
||
|
// we don't translate two-point lines
|
||
|
return scaledPoints;
|
||
|
}
|
||
|
|
||
|
const translation = minCoordinate - nextMinCoordinate;
|
||
|
|
||
|
const nextPoints = scaledPoints.map(
|
||
|
(scaledPoint) =>
|
||
|
scaledPoint.map((value, currentDimension) => {
|
||
|
return currentDimension === dimension ? value + translation : value;
|
||
|
}) as [number, number],
|
||
|
);
|
||
|
return nextPoints;
|
||
5 years ago
|
};
|