Skip to content

packages/core/src/features/viz/lib/numeric-range-interpolation.ts

Read as Markdown

This is the source snapshot used to build these API details. View this revision on GitHub.

Back to reference

1 import type { NumericDomain } from "./types.js";
2 
3 function endpoint(value: unknown, name: string): number {
4   if (typeof value !== "number" || !Number.isFinite(value))
5     throw new RangeError(`Numeric range ${name} must be finite.`);
6   return value;
7 }
8 
9 function range(value: NumericDomain, name: string): readonly [number, number] {
10   if (!Array.isArray(value) || value.length !== 2)
11     throw new TypeError(`Numeric range ${name} requires two endpoints.`);
12   return [endpoint(value[0], `${name}[0]`), endpoint(value[1], `${name}[1]`)];
13 }
14 
15 function interpolateEndpoint(from: number, to: number, progress: number): number {
16   if (progress === 0 || from === to) return from;
17   if (progress === 1) return to;
18   const difference = to - from;
19   const direct = from + difference * progress;
20   if (Number.isFinite(direct)) return direct;
21 
22   // Scaling avoids overflow in the subtraction for opposite, very large endpoints.
23   const scale = Math.max(Math.abs(from), Math.abs(to));
24   const scaled =
25     (from / scale + (to / scale - from / scale) * progress) * scale;
26   if (!Number.isFinite(scaled))
27     throw new RangeError("Numeric range interpolation must produce finite endpoints.");
28   return scaled;
29 }
30 
31 /**
32  * Linearly interpolates both endpoints of a finite numeric range.
33  *
34  * The returned pair is frozen. It preserves ascending, descending, and flat
35  * endpoint order for progress within zero through one. Progress outside that
36  * interval deliberately extrapolates, matching Pibbl's numeric tween behavior.
37  *
38  * @param from - Starting finite endpoint pair.
39  * @param to - Ending finite endpoint pair.
40  * @param progress - Finite interpolation progress supplied by an animation definition.
41  * @returns A frozen finite endpoint pair.
42  * @see {@link NumericDomain}
43  */
44 export function interpolateNumericRange(
45   from: NumericDomain,
46   to: NumericDomain,
47   progress: number,
48 ): NumericDomain {
49   const start = range(from, "from");
50   const end = range(to, "to");
51   if (typeof progress !== "number" || !Number.isFinite(progress))
52     throw new RangeError("Numeric range interpolation progress must be finite.");
53   return Object.freeze([
54     interpolateEndpoint(start[0], end[0], progress),
55     interpolateEndpoint(start[1], end[1], progress),
56   ]);
57 }
58 

Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.