Skip to content

Commit

Permalink
call "dispose()" on objects that fall off the cache because they're t…
Browse files Browse the repository at this point in the history
…oo big

This case could be detected manually by checking for a `false` return value,
but it seems to me that there'd be no case where you wouldn't want to call the
"dispose" function when this happens.
  • Loading branch information
TooTallNate committed Sep 4, 2012
1 parent bae577e commit cb30000
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/lru-cache.js
Expand Up @@ -135,7 +135,10 @@ function LRUCache (options) {
}

// oversized objects fall out of cache automatically.
if (hit.length > max) return false
if (hit.length > max) {
if (dispose) dispose(key, value)
return false
}

length += hit.length
lruList[hit.lu] = cache[key] = hit
Expand Down
19 changes: 19 additions & 0 deletions test/basic.js
Expand Up @@ -246,3 +246,22 @@ test("disposal function", function(t) {
t.equal(disposed, 3)
t.end()
})

test("disposal function on too big of item", function(t) {
var disposed = false
var cache = new LRU({
max: 1,
length: function (k) {
return k.length
},
dispose: function (k, n) {
disposed = n
}
})
var obj = [ 1, 2 ]

t.equal(disposed, false)
cache.set("obj", obj)
t.equal(disposed, obj)
t.end()
})

0 comments on commit cb30000

Please sign in to comment.