Skip to content

Commit

Permalink
chore: use keyList instead of keys for lru cache
Browse files Browse the repository at this point in the history
  • Loading branch information
Yash-Singh1 committed Mar 3, 2024
1 parent 5e11932 commit 458942e
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions server/src/lib/lru-cache.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
// Based off https://github.com/trekhleb/javascript-algorithms/blob/master/src/data-structures/lru-cache/LRUCacheOnMap.js

class LRUCache<K, V> extends Map<K, V> {
private capacity: number;
private keyList: K[];

constructor(capacity: number) {
super();
this.capacity = capacity;
this.keyList = [];
}

get(key: K) {
if (!super.has(key)) return undefined;
const val = super.get(key)!;
super.delete(key);
super.set(key, val);
return val;
this.keyList = [...this.keyList.filter((k) => k !== key), key];
return super.get(key);
}

set(key: K, val: V) {
super.delete(key);
super.set(key, val);

if (super.size > this.capacity) {
super.delete(super.keys().return!().value as K);
this.keyList = [...this.keyList.filter((k) => k !== key), key];
if (this.keyList.length > this.capacity) {
super.delete(this.keyList[0]);
this.keyList.shift();
}

return this;
Expand Down

0 comments on commit 458942e

Please sign in to comment.