import { Range, Range2D, Point2D, Size } from './types'; /** * Returns a closure for mapping values from one 1D range to another linearly. Values outside the initial range may be * mapped too. * * @param initial the range from which the value originates. * @param final the range to which the value should be mapped. */ export function linearTransform(initial: Range, final: Range): (value: number) => number { return (value: number): number => final.start + (final.end - final.start) * ((value - initial.start) / (initial.end - initial.start)); } /** * Returns a closure for mapping values from one 2D range to another linearly. Values outside the initial range may be * mapped too. * * @param initial the range from which the value originates. * @param final the range to which the value should be mapped. */ export function linearTransform2D(initial: Range2D, final: Range2D): (value: Point2D) => Point2D { const x = linearTransform(initial.x, final.x); const y = linearTransform(initial.y, final.y); return (value: Point2D): Point2D => ({ ...value, x: x(value.x), y: y(value.y), }); } /** * Creates a closure for scaling sizes. * @param original the original dimensions to which the input size is relative. * @param final the output dimensions to which the output size will be relative. */ export function sizeScale(original: Size, final: Size): (input: Size) => Size { const widthFactor = final.width / original.width; const heightFactor = final.height / original.height; return (input: Size): Size => ({ width: input.width * widthFactor, height: input.height * heightFactor, }); } /** * Creates a transform string for scaling an SVG object from one size to another. * @param original the original dimensions to which the input size is relative. * @param final the output dimensions to which the output size will be relative. */ export function svgSizeScale(original: Size, final: Size): string { const { width, height } = sizeScale(original, final)({ width: 1, height: 1 }); return `scale(${width},${height})`; } /** * Converts a point to an SVG coordinate for use in path data. * @param point the point to convert. */ export function svgCoordinate(point: Point2D): string { return `${point.x} ${point.y}`; } /** * Calcuates the square of the euclidean distance between two points. * @param a the first point * @param b the second point */ export function euclideanDistanceSquared(a: Point2D, b: Point2D): number { return (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y); }