2020-03-17 11:01:11 -07:00
|
|
|
import { Point } from "./types";
|
|
|
|
|
2020-05-20 16:21:37 +03:00
|
|
|
export const getSizeFromPoints = (points: readonly Point[]) => {
|
2020-03-23 13:05:07 +02:00
|
|
|
const xs = points.map((point) => point[0]);
|
|
|
|
const ys = points.map((point) => point[1]);
|
2020-03-17 11:01:11 -07:00
|
|
|
return {
|
|
|
|
width: Math.max(...xs) - Math.min(...xs),
|
|
|
|
height: Math.max(...ys) - Math.min(...ys),
|
|
|
|
};
|
2020-05-20 16:21:37 +03:00
|
|
|
};
|
2021-05-09 16:42:10 +01:00
|
|
|
|
2022-08-13 22:53:10 +05:00
|
|
|
/** @arg dimension, 0 for rescaling only x, 1 for y */
|
2020-05-20 16:21:37 +03:00
|
|
|
export const rescalePoints = (
|
2020-03-17 11:01:11 -07:00
|
|
|
dimension: 0 | 1,
|
2022-08-13 22:53:10 +05:00
|
|
|
newSize: number,
|
|
|
|
points: readonly Point[],
|
2022-08-16 21:51:43 +02:00
|
|
|
normalize: boolean,
|
2020-05-20 16:21:37 +03:00
|
|
|
): Point[] => {
|
2022-08-13 22:53:10 +05:00
|
|
|
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;
|
|
|
|
|
2022-08-16 21:51:43 +02:00
|
|
|
let nextMinCoordinate = Infinity;
|
|
|
|
|
|
|
|
const scaledPoints = points.map((point): Point => {
|
2022-08-13 22:53:10 +05:00
|
|
|
const newCoordinate = point[dimension] * scale;
|
|
|
|
const newPoint = [...point];
|
|
|
|
newPoint[dimension] = newCoordinate;
|
2022-08-16 21:51:43 +02:00
|
|
|
if (newCoordinate < nextMinCoordinate) {
|
|
|
|
nextMinCoordinate = newCoordinate;
|
|
|
|
}
|
2022-08-13 22:53:10 +05:00
|
|
|
return newPoint as unknown as Point;
|
|
|
|
});
|
2022-08-16 21:51:43 +02:00
|
|
|
|
|
|
|
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;
|
2020-05-20 16:21:37 +03:00
|
|
|
};
|