1/** 2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 17const TAG = 'DiskLruCache'; 18 19/** 20 * A class provides persistent operation for memory cache. 21 */ 22export default class DiskLruCache { 23 private readonly cache; 24 private readonly capacity; 25 26 constructor(capacity = 100) { 27 this.cache = new Map(); 28 this.capacity = capacity; 29 this.initMap(); //read cache from local 30 } 31 32 /** 33 * Init the cache whether the file has data. 34 */ 35 initMap(): void { 36 } 37 38 /** 39 * Get cache from disk. 40 * 41 * @param {string} key - key of the cache map 42 * @return {object} - target cache object 43 */ 44 getCache(key: string) { 45 if (this.cache.has(key)) { 46 // exist and update 47 const temp = this.cache.get(key); 48 //delete the old cache 49 this.cache.delete(key); 50 //update the cache to recent use 51 this.cache.set(key, temp); 52 //update local cache to recent use 53 return temp; 54 } 55 return -1; 56 } 57 58 /** 59 * Put cache to disk. 60 * 61 * @param {string} key - key of the cache map 62 * @param {object} value - value of the cache map 63 */ 64 putCache(key: string, value: object | string): void { 65 if (this.cache.has(key)) { 66 // exist and update 67 this.cache.delete(key); 68 } else if (this.cache.size >= this.capacity) { 69 // if size > capacity ,remove the old 70 this.remove(this.cache.keys().next().value); 71 } 72 //update the cache to recent use 73 this.cache.set(key, value); 74 } 75 76 /** 77 * Remove cache of corresponding key. 78 * 79 * @param {string} key - key of the cache map 80 */ 81 remove(key: string): void { 82 this.cache.delete(key); 83 } 84 85 /** 86 * Clear cache of disk. 87 */ 88 clear(): void { 89 this.cache.clear(); 90 } 91}