Created
December 14, 2018 23:59
-
-
Save overcyn/b0a7601d123e420d73876f65aee402a9 to your computer and use it in GitHub Desktop.
LRU Cache
This file contains hidden or 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 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