Last active
December 21, 2020 03:28
-
-
Save or9/2627851e20aba4aeef6a2da26dcfc798 to your computer and use it in GitHub Desktop.
Linked list exercise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LFUCache { | |
constructor(capacity) { | |
this.capacity = capacity; | |
this.lru = []; | |
this.cache = Object.create(null, {}); | |
} | |
get(key) { | |
if (!this.cache[key]) return -1; | |
this.cache[key].usage += 1; | |
return this.cache[key].value; | |
} | |
set(key, val) { | |
let addNewCacheItem = false; | |
this.cache[key] = { | |
...this.cache[key], | |
usage: this.cache?.[key]?.usage ?? 0, | |
value: val, | |
lruKey: key, | |
}; | |
const isExistingIndex = this.lru.findIndex(({ lruKey}) => lruKey === key); | |
if (isExistingIndex > -1) { | |
this.lru[isExistingIndex] = this.cache[key]; | |
} else { | |
addNewCacheItem = true; | |
} | |
if (this.lru.length > this.capacity) { | |
const { lruKey } = this.lru.sort((x, y) => { | |
if (x.usage >= y.usage) return 1; | |
else return -1; | |
}) | |
.shift(); | |
delete this.cache[lruKey]; | |
if (addNewCacheItem) { | |
this.lru.push(this.cache[key]); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment