63 lines
1.4 KiB
TypeScript
63 lines
1.4 KiB
TypeScript
/**
|
||
* Text Wrap - width-measurement 缓存
|
||
*
|
||
* 要求:
|
||
* - 模块级常驻缓存(跨调用复用)
|
||
* - 有容量上限(避免内存无限增长)
|
||
* - Key 必须确定性(由上层拼接传入)
|
||
*
|
||
* 说明:
|
||
* - 这里实现一个最小 LRU:Map 维护插入顺序;get 时“刷新”为最新。
|
||
* - 缓存 value 允许是 Promise,以便并发请求去重(同 key 只测一次)。
|
||
*/
|
||
|
||
export class LruCache<V> {
|
||
private readonly maxSize: number;
|
||
private readonly map: Map<string, V>;
|
||
|
||
constructor(maxSize: number) {
|
||
if (!Number.isFinite(maxSize) || maxSize <= 0) {
|
||
throw new Error('LRU 缓存 maxSize 必须为正数。');
|
||
}
|
||
this.maxSize = Math.floor(maxSize);
|
||
this.map = new Map();
|
||
}
|
||
|
||
get(key: string): V | undefined {
|
||
const v = this.map.get(key);
|
||
if (v === undefined) return undefined;
|
||
// 刷新为最新
|
||
this.map.delete(key);
|
||
this.map.set(key, v);
|
||
return v;
|
||
}
|
||
|
||
set(key: string, value: V): void {
|
||
if (this.map.has(key)) {
|
||
this.map.delete(key);
|
||
}
|
||
this.map.set(key, value);
|
||
|
||
if (this.map.size > this.maxSize) {
|
||
// 淘汰最旧的
|
||
const oldestKey = this.map.keys().next().value as string | undefined;
|
||
if (oldestKey !== undefined) {
|
||
this.map.delete(oldestKey);
|
||
}
|
||
}
|
||
}
|
||
|
||
delete(key: string): void {
|
||
this.map.delete(key);
|
||
}
|
||
|
||
clear(): void {
|
||
this.map.clear();
|
||
}
|
||
|
||
size(): number {
|
||
return this.map.size;
|
||
}
|
||
}
|
||
|