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 16import { Log } from '../utils/Log'; 17 18const TAG = 'DiskLruCache'; 19 20/** 21 * A class provides persistent operation for memory cache. 22 */ 23export default class DiskLruCache { 24 private readonly cache; 25 private readonly capacity; 26 27 constructor(capacity = 100) { 28 this.cache = new Map(); 29 this.capacity = capacity; 30 this.initMap(); //read cache from local 31 } 32 33 /** 34 * Init the cache whether the file has data. 35 */ 36 initMap(): void { 37 } 38 39 /** 40 * Get cache from disk. 41 * 42 * @param {string} key - key of the cache map 43 * @return {object} - target cache object 44 */ 45 getCache(key: string) { 46 if (this.cache.has(key)) { 47 // exist and update 48 const temp = this.cache.get(key); 49 //delete the old cache 50 this.cache.delete(key); 51 //update the cache to recent use 52 this.cache.set(key, temp); 53 //update local cache to recent use 54 return temp; 55 } 56 return -1; 57 } 58 59 /** 60 * Put cache to disk. 61 * 62 * @param {string} key - key of the cache map 63 * @param {object} value - value of the cache map 64 */ 65 putCache(key: string, value: object | string): void { 66 if (this.cache.has(key)) { 67 // exist and update 68 this.cache.delete(key); 69 } else if (this.cache.size >= this.capacity) { 70 // if size > capacity ,remove the old 71 this.remove(this.cache.keys().next().value); 72 } 73 //update the cache to recent use 74 this.cache.set(key, value); 75 } 76 77 /** 78 * Remove cache of corresponding key. 79 * 80 * @param {string} key - key of the cache map 81 */ 82 remove(key: string): void { 83 this.cache.delete(key); 84 } 85 86 /** 87 * Clear cache of disk. 88 */ 89 clear(): void { 90 this.cache.clear(); 91 } 92}