Skip to content

Commit

Permalink
simpler cache
Browse files Browse the repository at this point in the history
  • Loading branch information
hanydd committed Dec 5, 2024
1 parent 5f3209e commit 7371f72
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 16 deletions.
8 changes: 3 additions & 5 deletions src/document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,9 @@ function overwriteFetch() {
if (url.pathname.includes("/player/wbi/playurl")) {
const cid = url.searchParams.get("cid");
if (!playInfoCache.getFromCache(cid) && res?.data?.dash?.video) {
playInfoCache.setupCache(cid).push(
...res.data.dash.video.map((v) => ({
id: v.id,
frameRate: parseFloat(v.frameRate),
}))
playInfoCache.set(
cid,
res.data.dash.video.map((v) => ({ id: v.id, frameRate: parseFloat(v.frameRate) }))
);
}
}
Expand Down
29 changes: 18 additions & 11 deletions src/utils/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export class DataCache<T extends string, V> {
private init: () => V;
private cacheLimit: number;

constructor(init: () => V, cacheLimit = 2000) {
constructor(init?: () => V, cacheLimit = 2000) {
this.cache = {};
this.init = init;
this.cacheLimit = cacheLimit;
Expand All @@ -17,17 +17,17 @@ export class DataCache<T extends string, V> {
return this.cache[key];
}

public set(key: T, value: V): void {
this.cache[key] = {
...value,
lastUsed: Date.now(),
};
this.gc();
}

public setupCache(key: T): V & CacheRecord {
if (!this.cache[key]) {
this.cache[key] = {
...this.init(),
lastUsed: Date.now(),
};

if (Object.keys(this.cache).length > this.cacheLimit) {
const oldest = Object.entries(this.cache).reduce((a, b) => (a[1].lastUsed < b[1].lastUsed ? a : b));
delete this.cache[oldest[0]];
}
if (!this.cache[key] && this.init) {
this.set(key, this.init());
}

return this.cache[key];
Expand All @@ -38,4 +38,11 @@ export class DataCache<T extends string, V> {

return !!this.cache[key];
}

private gc(): void {
if (Object.keys(this.cache).length > this.cacheLimit) {
const oldest = Object.entries(this.cache).reduce((a, b) => (a[1].lastUsed < b[1].lastUsed ? a : b));
delete this.cache[oldest[0]];
}
}
}

0 comments on commit 7371f72

Please sign in to comment.