UNPKG

583 BPlain TextView Raw
1import { CacheDelegate } from "./interfaces";
2
3export default class Cache<K, CK, V> {
4 public hits = 0;
5 public misses = 0;
6 private store = new Map<CK, V>();
7 constructor(private delegate: CacheDelegate<K, CK, V>) {}
8
9 public get(key: K): V {
10 const cacheKey = this.delegate.cacheKey(key);
11 let value = this.store.get(cacheKey);
12 if (value === undefined) {
13 this.misses++;
14 value = this.delegate.create(key);
15 this.store.set(cacheKey, value);
16 } else {
17 this.hits++;
18 }
19 return value;
20 }
21
22 public clear() {
23 this.store.clear();
24 }
25}