Skip to content

Instantly share code, notes, and snippets.

@chrisbnt
Created November 10, 2015 01:00
Show Gist options
  • Save chrisbnt/7ecbaa113f2047408f01 to your computer and use it in GitHub Desktop.
Save chrisbnt/7ecbaa113f2047408f01 to your computer and use it in GitHub Desktop.
Dirt simple LRU cache
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