3 A cache object that deletes the least-recently-used items.
8 var LRU = require("lru-cache")
10 , length: function (n) { return n * 2 }
11 , dispose: function (key, n) { n.close() }
12 , maxAge: 1000 * 60 * 60 }
13 , cache = LRU(options)
14 , otherCache = LRU(50) // sets just the max size
16 cache.set("key", "value")
17 cache.get("key") // "value"
19 cache.reset() // empty the cache
22 If you put more stuff in it, then items will fall out.
24 If you try to put an oversized thing in it, then it'll fall out right
29 * `max` The maximum size of the cache, checked by applying the length
30 function to all values in the cache. Not setting this is kind of
31 silly, since that's the whole purpose of this lib, but it defaults
33 * `maxAge` Maximum age in ms. Items are not pro-actively pruned out
34 as they age, but if you try to get an item that is too old, it'll
35 drop it and return undefined instead of giving it to you.
36 * `length` Function that is used to calculate the length of stored
37 items. If you're storing strings or buffers, then you probably want
38 to do something like `function(n){return n.length}`. The default is
39 `function(n){return 1}`, which is fine if you want to store `n`
41 * `dispose` Function that is called on items when they are dropped
42 from the cache. This can be handy if you want to close file
43 descriptors or do other cleanup tasks when items are no longer
44 accessible. Called with `key, value`. It's called *before*
45 actually removing the item from the internal cache, so if you want
46 to immediately put it back in, you'll have to do that in a
47 `nextTick` or `setTimeout` callback or it won't do anything.
48 * `stale` By default, if you set a `maxAge`, it'll only actually pull
49 stale items out of the cache when you `get(key)`. (That is, it's
50 not pre-emptively doing a `setTimeout` or anything.) If you set
51 `stale:true`, it'll return the stale value before deleting it. If
52 you don't set this, then it'll return `undefined` when you try to
53 get a stale entry, as if it had already been deleted.
60 Both of these will update the "recently used"-ness of the key.
61 They do what you think.
65 Returns the key value (or `undefined` if not found) without
66 updating the "recently used"-ness of the key.
68 (If you find yourself using this a lot, you *might* be using the
69 wrong sort of data structure, but there are some use cases where
74 Deletes a key out of the cache.
78 Clear the cache entirely, throwing away all values.
82 Check if a key is in the cache, without updating the recent-ness
83 or deleting it for being stale.
85 * `forEach(function(value,key,cache), [thisp])`
87 Just like `Array.prototype.forEach`. Iterates over all the keys
88 in the cache, in order of recent-ness. (Ie, more recently used
89 items are iterated over first.)
93 Return an array of the keys in the cache.
97 Return an array of the values in the cache.