* @template T * @param {T} a * @param {T} b * @returns {(t: number) => T}
(a, b)
| 17 | * @returns {(t: number) => T} |
| 18 | */ |
| 19 | function get_interpolator(a, b) { |
| 20 | if (a === b || a !== a) return () => a; |
| 21 | |
| 22 | const type = typeof a; |
| 23 | if (type !== typeof b || Array.isArray(a) !== Array.isArray(b)) { |
| 24 | throw new Error('Cannot interpolate values of different type'); |
| 25 | } |
| 26 | |
| 27 | if (Array.isArray(a)) { |
| 28 | const arr = /** @type {Array<any>} */ (b).map((bi, i) => { |
| 29 | return get_interpolator(/** @type {Array<any>} */ (a)[i], bi); |
| 30 | }); |
| 31 | |
| 32 | // @ts-ignore |
| 33 | return (t) => arr.map((fn) => fn(t)); |
| 34 | } |
| 35 | |
| 36 | if (type === 'object') { |
| 37 | if (!a || !b) { |
| 38 | throw new Error('Object cannot be null'); |
| 39 | } |
| 40 | |
| 41 | if (is_date(a) && is_date(b)) { |
| 42 | const an = a.getTime(); |
| 43 | const bn = b.getTime(); |
| 44 | const delta = bn - an; |
| 45 | |
| 46 | // @ts-ignore |
| 47 | return (t) => new Date(an + t * delta); |
| 48 | } |
| 49 | |
| 50 | const keys = Object.keys(b); |
| 51 | |
| 52 | /** @type {Record<string, (t: number) => T>} */ |
| 53 | const interpolators = {}; |
| 54 | keys.forEach((key) => { |
| 55 | // @ts-ignore |
| 56 | interpolators[key] = get_interpolator(a[key], b[key]); |
| 57 | }); |
| 58 | |
| 59 | // @ts-ignore |
| 60 | return (t) => { |
| 61 | /** @type {Record<string, any>} */ |
| 62 | const result = {}; |
| 63 | keys.forEach((key) => { |
| 64 | result[key] = interpolators[key](t); |
| 65 | }); |
| 66 | return result; |
| 67 | }; |
| 68 | } |
| 69 | |
| 70 | if (type === 'number') { |
| 71 | const delta = /** @type {number} */ (b) - /** @type {number} */ (a); |
| 72 | // @ts-ignore |
| 73 | return (t) => a + t * delta; |
| 74 | } |
| 75 | |
| 76 | // for non-numeric values, snap to the final value immediately |