Skip to content

Commit

Permalink
add peek(key) function
Browse files Browse the repository at this point in the history
  • Loading branch information
isaacs committed Mar 25, 2013
1 parent e57ac87 commit 5b43b23
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 13 deletions.
9 changes: 9 additions & 0 deletions README.md
Expand Up @@ -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.
Expand Down
34 changes: 23 additions & 11 deletions lib/lru-cache.js
Expand Up @@ -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) {
Expand Down
4 changes: 2 additions & 2 deletions test/basic.js
Expand Up @@ -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)
Expand Down

0 comments on commit 5b43b23

Please sign in to comment.