Skip to content

Commit

Permalink
Add cache.pop(), which evicts the oldest item, without affecting "max"
Browse files Browse the repository at this point in the history
  • Loading branch information
mcavage committed Nov 21, 2013
1 parent a81fabf commit d9c770c
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/lru-cache.js
Expand Up @@ -206,6 +206,12 @@ function LRUCache (options) {
return get(key, false)
}

this.pop = function () {
var hit = lruList[lru]
del(hit)
return hit || null
}

function get (key, doUse) {
var hit = cache[key]
if (hit) {
Expand Down
40 changes: 40 additions & 0 deletions test/basic.js
Expand Up @@ -327,3 +327,43 @@ test("least recently set w/ peek", function (t) {
t.equal(cache.get("a"), undefined)
t.end()
})

test("pop the least used item", function (t) {
var cache = new LRU(3)
, last

cache.set("a", "A")
cache.set("b", "B")
cache.set("c", "C")

t.equal(cache.length, 3)
t.equal(cache.max, 3)

// Ensure we pop a, c, b
cache.get("b", "B")

last = cache.pop()
t.equal(last.key, "a")
t.equal(last.value, "A")
t.equal(cache.length, 2)
t.equal(cache.max, 3)

last = cache.pop()
t.equal(last.key, "c")
t.equal(last.value, "C")
t.equal(cache.length, 1)
t.equal(cache.max, 3)

last = cache.pop()
t.equal(last.key, "b")
t.equal(last.value, "B")
t.equal(cache.length, 0)
t.equal(cache.max, 3)

last = cache.pop()
t.equal(last, null)
t.equal(cache.length, 0)
t.equal(cache.max, 3)

t.end()
})

0 comments on commit d9c770c

Please sign in to comment.