| // Copyright 2021 The Chromium Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file. |
| |
| export class LRUMemoryCacheObject { |
| capacity: number; |
| |
| cache: Map<string, any>; |
| |
| /** |
| * Creates a new LRUMemoryCacheObject instance. |
| * |
| * @param capacity The max capacity of the LRUMemoryCacheObject. |
| */ |
| constructor(capacity: number) { |
| this.capacity = capacity; |
| this.cache = new Map(); |
| } |
| |
| /** |
| * Reads the cached object. |
| * |
| * @param key The accessor for a value in the LRUMemoryCacheObject. |
| */ |
| read(key: string): any { |
| if (!this.cache.has(key)) { |
| return undefined; |
| } |
| const value = this.cache.get(key); |
| this.cache.delete(key); |
| this.cache.set(key, value); |
| return value; |
| } |
| |
| /** |
| * Writes value using key in the cache. |
| * |
| * @param key The key to use for LRUMemoryCacheObject. |
| * @param value The value to be set. |
| */ |
| write(key: string, value: any): void { |
| if (this.cache.has(key)) { |
| this.cache.delete(key); |
| } |
| this.cache.set(key, value); |
| if (this.cache.size > this.capacity) { |
| this.cache.delete(this.cache.keys().next().value!); |
| } |
| } |
| |
| /** |
| * Deletes a key from the cache. |
| * |
| * @param key The key to delete in LRUMemoryCacheObject. |
| */ |
| delete(key: string): void { |
| this.cache.delete(key); |
| } |
| |
| /** |
| * Resets the cache. |
| */ |
| clear(): void { |
| this.cache.clear(); |
| } |
| } |