Created
November 10, 2015 01:00
-
-
Save chrisbnt/7ecbaa113f2047408f01 to your computer and use it in GitHub Desktop.
Dirt simple LRU cache
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
module.exports = (options = {})-> | |
cache = {} | |
cacheSize = 0 | |
maxKeys = options.maxKeys || 50 | |
seq = 1 | |
get: (key)-> | |
if c = cache[key] | |
c.used = seq++ | |
return c.value | |
set: (key, value)-> | |
@freeLRU() if cacheSize >= maxKeys && !cache[key] | |
cache[key] = | |
used: seq++ | |
value: value | |
cacheSize = Object.keys(cache).length | |
return cacheSize | |
freeLRU: -> | |
oldestKey = null | |
oldest = null | |
for key, c of cache | |
if !oldestKey || c.used < oldest | |
oldestKey = key | |
oldest = c.used | |
delete cache[oldestKey] if oldestKey | |
return oldestKey |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment