/** * 可限制尺寸的键值对缓存 * */ export class LimitKeyValueCache { options: { limit: number; popSize: number } /** * @param options.limit {number} 限制尺寸 * @param options.popSize {number} 当超过尺寸时,删除多少元素,默认为 1 */ constructor(options: { limit: number; popSize?: number }) { this.options = Object.assign({ limit: 921024, popSize: 1 }, options) } caches = new Map() keySet = new Set() _size = 0 set(key: K, value: V) { if (this.keySet.size >= this.options.limit) { this._pop(this.options.popSize) } this.keySet.add(key) if (this.caches) return this.caches.set(key, value) } get(key: K) { return this.caches.get(key) } has(key: K) { return this.caches.has(key) } delete(key: K) { this.keySet.delete(key) return this.caches.delete(key) } _pop(popSize: number) { let count = 0 for (let item of this.keySet) { if (count < popSize) { this.keySet.delete(item) this.caches.delete(item) count++ } else { break } } } get size() { return this.keySet.size } }