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