Permalink
Browse files

add peek(key) function

  • Loading branch information...
isaacs committed Mar 25, 2013
1 parent e57ac87 commit 5b43b2369bcde60d509c5db01fbee3cfb773f0b8
Showing with 34 additions and 13 deletions.
  1. +9 −0 README.md
  2. +23 −11 lib/lru-cache.js
  3. +2 −2 test/basic.js
View
@@ -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
@@ -191,22 +191,34 @@ function LRUCache (options) {
}
return true
}
-
- this._get = function (key) {
- return cache[key]
+
+ this.peek = function (key) {
+ var hit = get(key)
+ return hit && hit.value
}
this.get = function (key) {
- if (!hOP(cache, key)) return
+ var hit = get(key)
+ var ret
+ if (hit) {
+ delete lruList[hit.lu]
+ hit.lu = mru ++
+ lruList[hit.lu] = hit
+ ret = hit.value
+ }
+ return ret
+ }
+
+ // Does not update least-recently-used status
+ function get(key) {
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
+ }
}
- delete lruList[hit.lu]
- hit.lu = mru ++
- lruList[hit.lu] = hit
- return hit.value
+ return hit
}
this.del = function (key) {
View
@@ -300,12 +300,12 @@ test("stale", function(t) {
}, 15)
})
-test("least recently set w/ _get", function (t) {
+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")
- cache._get("a")
t.equal(cache.get("c"), "C")
t.equal(cache.get("b"), "B")
t.equal(cache.get("a"), undefined)

0 comments on commit 5b43b23

Please sign in to comment.