Skip to content

Commit

Permalink
Recalculate length on update
Browse files Browse the repository at this point in the history
fixes isaacs#41
  • Loading branch information
Javier Mendiara Cañardo committed May 4, 2015
1 parent 278d05f commit a607a32
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
12 changes: 11 additions & 1 deletion lib/lru-cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,20 +150,30 @@ LRUCache.prototype.dumpLru = function () {
LRUCache.prototype.set = function (key, value, maxAge) {
maxAge = maxAge || this._maxAge
var now = maxAge ? Date.now() : 0
var len = this._lengthCalculator(value)

if (hOP(this._cache, key)) {
if (len > this._max) {
del(this, this._cache[key])
return false
}
// dispose of the old one before overwriting
if (this._dispose)
this._dispose(key, this._cache[key].value)

this._cache[key].now = now
this._cache[key].maxAge = maxAge
this._cache[key].value = value
this._length += (len - this._cache[key].length)
this._cache[key].length = len
this.get(key)

if (this._length > this._max)
trim(this)

return true
}

var len = this._lengthCalculator(value)
var hit = new Entry(key, value, this._mru++, len, now, maxAge)

// oversized objects fall out of cache automatically.
Expand Down
26 changes: 26 additions & 0 deletions test/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,32 @@ test("lru recently gotten with weighed length", function (t) {
t.end()
})

test("lru recently updated with weighed length", function (t) {
var cache = new LRU({
max: 8,
length: function (item) { return item.length }
})
cache.set("a", "A")
cache.set("b", "BB")
cache.set("c", "CCC")
t.equal(cache.length, 6) //CCC BB A
cache.set("a", "+A")
t.equal(cache.length, 7) //+A CCC BB
cache.set("b", "++BB")
t.equal(cache.length, 6) //++BB +A
t.equal(cache.get("c"), undefined)

cache.set("c", "oversized")
t.equal(cache.length, 6) //++BB +A
t.equal(cache.get("c"), undefined)

cache.set("a", "oversized")
t.equal(cache.length, 4) //++BB
t.equal(cache.get("a"), undefined)
t.equal(cache.get("b"), "++BB")
t.end()
})

test("set returns proper booleans", function(t) {
var cache = new LRU({
max: 5,
Expand Down

0 comments on commit a607a32

Please sign in to comment.