| 20 | * 用于需要重复插值相同起始和目标值的情况 |
| 21 | */ |
| 22 | export class CachedInterpolator<T> { |
| 23 | private from?: T; |
| 24 | private to?: T; |
| 25 | private interpolator: InterpolatorFunction<T>; |
| 26 | private cache: Map<number, T> = new Map(); |
| 27 | |
| 28 | constructor(interpolator: InterpolatorFunction<T>) { |
| 29 | this.interpolator = interpolator; |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * 设置插值范围 |
| 34 | * @param from 起始值 |
| 35 | * @param to 目标值 |
| 36 | */ |
| 37 | setRange(from: T, to: T): void { |
| 38 | if (this.from !== from || this.to !== to) { |
| 39 | this.from = from; |
| 40 | this.to = to; |
| 41 | this.cache.clear(); |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * 获取插值结果 |
| 47 | * @param t 插值参数 |
| 48 | * @returns 插值结果 |
| 49 | */ |
| 50 | get(t: number): T { |
| 51 | if (!this.from || !this.to) { |
| 52 | throw new Error('插值范围未设置'); |
| 53 | } |
| 54 | |
| 55 | if (!this.cache.has(t)) { |
| 56 | const result = this.interpolator(this.from, this.to, t); |
| 57 | this.cache.set(t, result); |
| 58 | } |
| 59 | |
| 60 | return this.cache.get(t)!; |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * 清空缓存 |
| 65 | */ |
| 66 | clearCache(): void { |
| 67 | this.cache.clear(); |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | /** |
| 72 | * 插值工具类 |
nothing calls this directly
no outgoing calls
no test coverage detected