Skip to content

Commit 8f7ee8a

Browse files
authored
Merge pull request #13 from RootUp/brave-WeakLRUCache-fix
fix WeakLRUCache
2 parents 7f35c31 + 04d9de1 commit 8f7ee8a

File tree

1 file changed

+17
-15
lines changed

1 file changed

+17
-15
lines changed

SmuggleShield/background.js

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,38 +13,40 @@ class WeakLRUCache {
1313
constructor(maxSize) {
1414
this.maxSize = maxSize;
1515
this.cache = new Map();
16-
this.keyMap = new WeakMap();
16+
this.keyMap = new Map();
1717
}
1818

1919
get(key) {
20-
const keyObj = this.keyMap.get(key);
21-
if (!keyObj) return undefined;
22-
const value = this.cache.get(keyObj);
20+
const keyString = this.getKeyString(key);
21+
const value = this.cache.get(keyString);
2322
if (value) {
24-
this.cache.delete(keyObj);
25-
this.cache.set(keyObj, value);
23+
this.cache.delete(keyString);
24+
this.cache.set(keyString, value);
2625
}
2726
return value;
2827
}
2928

3029
set(key, value) {
31-
let keyObj = this.keyMap.get(key);
32-
if (!keyObj) {
33-
keyObj = { key };
34-
this.keyMap.set(key, keyObj);
35-
}
36-
if (this.cache.has(keyObj)) {
37-
this.cache.delete(keyObj);
30+
const keyString = this.getKeyString(key);
31+
if (this.cache.has(keyString)) {
32+
this.cache.delete(keyString);
3833
} else if (this.cache.size >= this.maxSize) {
3934
const oldestKey = this.cache.keys().next().value;
4035
this.cache.delete(oldestKey);
4136
}
42-
this.cache.set(keyObj, value);
37+
this.cache.set(keyString, value);
38+
this.keyMap.set(keyString, key);
4339
}
4440

4541
clear() {
4642
this.cache.clear();
47-
this.keyMap = new WeakMap();
43+
this.keyMap.clear();
44+
}
45+
46+
getKeyString(key) {
47+
return typeof key === 'object' ?
48+
JSON.stringify(key) :
49+
String(key);
4850
}
4951
}
5052

0 commit comments

Comments
 (0)