import { Range, Point2D, Range2D, Selection2D } from './types'; /** * Returns a copy of the input range, with the start and end flipped if the input's start is greater than the input's * end. * @param range the input range. */ export function forwardRange(range: Range): Range { return { start: range.start < range.end ? range.start : range.end, end: range.start < range.end ? range.end : range.start, }; } /** * Returns a closure for checking whether points fall within the specified 2D range. * @param range the range to check. */ export function inRange2D(range: Range2D): (point: Point2D) => boolean { const fRange = { x: forwardRange(range.x), y: forwardRange(range.y), }; return (point: Point2D): boolean => point.x >= fRange.x.start && point.x <= fRange.x.end && point.y >= fRange.y.start && point.y <= fRange.y.end; } /** * Converts a selection in 2D to a range in 2D. * @param member the selection to convert. */ export function selection2DToRange2D(selection: Selection2D): Range2D { return { x: { start: selection.start.x, end: selection.end.x, }, y: { start: selection.start.y, end: selection.end.y, }, }; } /** * Divides an input range into a reasonable number of ticks for visual display on an axis. * @param domain the input range to divide. * @param cScale used in recursion only; adjusts the tick resolution. */ export function autoTicks(domain: Range, cScale: number = 1.0): number[] { const sFig = Math.pow(10.0, Math.floor(Math.log10(domain.end))); const r: number[] = []; const lRange: Range = { start: Math.floor(domain.start / sFig) * sFig, end: Math.ceil(domain.end / sFig) * sFig }; for (let i = lRange.start; i <= lRange.end; i += sFig * cScale) { r.push(i); } if (r.length <= 2) return [Math.ceil(domain.start), Math.floor(domain.end)]; return r.length > 10 ? autoTicks(domain, cScale * 2) : r; } /** * Expands the width of the range by a given factor. * @param domain the range to expand. * @param factor the percentage by which to expand the range; for example, 0.1 adds 10% of the range width to each side. */ export function expandRange(domain: Range, factor: number): Range { const length = domain.end - domain.start; return { start: domain.start - length * factor, end: domain.end + length * factor, }; } /** * Expands the width of the range by a given factor, then rounds the starts and ends to the nearest integer. * @param domain the range to expand. * @param factor the percentage by which to expand the range; for example, 0.1 adds 10% of the range width to each side. */ export function expandRangeI(domain: Range, factor: number): Range { const length = domain.end - domain.start; return { start: Math.round(domain.start - length * factor), end: Math.round(domain.end + length * factor), }; }