Skip to content

Instantly share code, notes, and snippets.

@overcyn
Created December 14, 2018 23:59
Show Gist options
  • Select an option

  • Save overcyn/b0a7601d123e420d73876f65aee402a9 to your computer and use it in GitHub Desktop.

Select an option

Save overcyn/b0a7601d123e420d73876f65aee402a9 to your computer and use it in GitHub Desktop.
LRU Cache
class Cache {
constructor() {
this.theCache = {}
}
setImageById(id, image) {
let numberOfImages = Object.keys(this.cache).length
if (numberOfImages > 50) {
let keyOfOldest;
for(key in this.theCache) {
if (!keyOfOldest) {
keyOfOldest = key
} else {
if (this.cache[keyOfOldest].date > this.theCache[key].date) {
keyOfOldest = key
}
}
}
this.theCache.remove(keyOfOldest)
}
this.theCache[id] = {image, date: Date.now}
}
getImageById(id) {
this.theCache[id].date = Date.now
return this.theCache[id].image
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment