| | import { |
| | getDecimalPlaces, |
| | applyPrecision, |
| | getRandomNumberGenerator, |
| | generateFractions, |
| | } from './helpers' |
| |
|
| | export interface GenerateRangeOptions { |
| | |
| | min?: number |
| | |
| | max?: number |
| | |
| | baseline?: number |
| | |
| | samples: number |
| | |
| | jitter?: number |
| | |
| | precision?: number |
| | |
| | seed?: (() => number) | number |
| | } |
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | export const generateRange = ({ |
| | min = 0, |
| | max = 100, |
| | baseline = 0, |
| | samples, |
| | jitter = 0.66, |
| | precision = 0, |
| | seed, |
| | }: GenerateRangeOptions) => { |
| | |
| | if (!Number.isInteger(samples) || samples < 1) { |
| | throw new Error(`"samples" must be an integer ≥1; got ${samples}`) |
| | } |
| | if (jitter < 0 || jitter > 1) { |
| | throw new Error(`"jitter" must be between 0 and 1; got ${jitter}`) |
| | } |
| | if (precision < 0) { |
| | throw new Error(`"precision" must be ≥0; got ${precision}`) |
| | } |
| | if (baseline !== undefined && (baseline < min || baseline > max)) { |
| | throw new Error(`"baseline" (${baseline}) must be within [min, max]`) |
| | } |
| |
|
| | const span = max - min |
| | |
| | const baselineFraction = (baseline! - min) / span |
| | const baselineInterior = baseline! > min && baseline! < max |
| |
|
| | |
| | const endpointFracs: number[] = [] |
| | if (baseline !== min) endpointFracs.push(0) |
| | if (baseline !== max) endpointFracs.push(1) |
| | const endpointCount = endpointFracs.length |
| |
|
| | if (samples < endpointCount) { |
| | throw new Error(`samples (${samples}) less than available endpoints (${endpointCount})`) |
| | } |
| |
|
| | |
| | const interiorCount = samples - endpointCount |
| | |
| | const rawInteriorCount = interiorCount + (baselineInterior ? 1 : 0) |
| |
|
| | |
| | const random = getRandomNumberGenerator(seed) |
| | const decimalPlaces = getDecimalPlaces(precision) |
| |
|
| | |
| | const rawFractions = generateFractions(rawInteriorCount + 2, jitter, random) |
| | |
| | const interiorFractions = rawFractions.slice(1, -1) |
| |
|
| | |
| | if (baselineInterior) { |
| | |
| | let closestIdx = 0 |
| | let minDiff = Math.abs(interiorFractions[0] - baselineFraction) |
| | for (let i = 1; i < interiorFractions.length; i++) { |
| | const diff = Math.abs(interiorFractions[i] - baselineFraction) |
| | if (diff < minDiff) { |
| | minDiff = diff |
| | closestIdx = i |
| | } |
| | } |
| | interiorFractions.splice(closestIdx, 1) |
| | } |
| | |
| |
|
| | |
| | const combinedFractions = [...endpointFracs, ...interiorFractions].sort((a, b) => a - b) |
| |
|
| | |
| | return combinedFractions.map(fraction => { |
| | let value = min + span * fraction |
| | if (precision > 0) { |
| | const factor = Math.round(value / precision) |
| | value = factor * precision |
| | value = applyPrecision(value, decimalPlaces) |
| | } |
| |
|
| | return value |
| | }) |
| | } |
| |
|