Browse files

add peek(key) function

Basically the same as get(key), but without updating the
recently-used-ness.

Close #19
Close #20
  • Loading branch information...
1 parent 14189c8 commit 2ebfde2d6f78a1ad5401e7c5a3c13743ac6729d4 @isaacs committed Mar 25, 2013
Showing with 41 additions and 5 deletions.
  1. +9 −0 README.md
  2. +20 −5 lib/lru-cache.js
  3. +12 −0 test/basic.js
View
9 README.md
@@ -60,6 +60,15 @@ away.
Both of these will update the "recently used"-ness of the key.
They do what you think.
+* `peek(key)`
+
+ Returns the key value (or `undefined` if not found) without
+ updating the "recently used"-ness of the key.
+
+ (If you find yourself using this a lot, you *might* be using the
+ wrong sort of data structure, but there are some use cases where
+ it's handy.)
+
* `del(key)`
Deletes a key out of the cache.
View
25 lib/lru-cache.js
@@ -193,16 +193,31 @@ function LRUCache (options) {
}
this.get = function (key) {
- if (!hOP(cache, key)) return
+ return get(key, true)
+ }
+
+ this.peek = function (key) {
+ return get(key, false)
+ }
+
+ function get (key, doUse) {
var hit = cache[key]
- if (maxAge && (Date.now() - hit.now > maxAge)) {
- this.del(key)
- return allowStale ? hit.value : undefined
+ if (hit) {
+ if (maxAge && (Date.now() - hit.now > maxAge)) {
+ del(hit)
+ if (!allowStale) hit = undefined
+ } else {
+ if (doUse) use(hit)
+ }
+ if (hit) hit = hit.value
}
+ return hit
+ }
+
+ function use (hit) {
shiftLU(hit)
hit.lu = mru ++
lruList[hit.lu] = hit
- return hit.value
}
this.del = function (key) {
View
12 test/basic.js
@@ -315,3 +315,15 @@ test("lru update via set", function(t) {
t.equal(cache.get('qux'), 4)
t.end()
})
+
+test("least recently set w/ peek", function (t) {
+ var cache = new LRU(2)
+ cache.set("a", "A")
+ cache.set("b", "B")
+ t.equal(cache.peek("a"), "A")
+ cache.set("c", "C")
+ t.equal(cache.get("c"), "C")
+ t.equal(cache.get("b"), "B")
+ t.equal(cache.get("a"), undefined)
+ t.end()
+})

0 comments on commit 2ebfde2

Please sign in to comment.