Skip to content

Commit

Permalink
forEach iterates over all entries
Browse files Browse the repository at this point in the history
  • Loading branch information
timjk authored and isaacs committed Apr 15, 2015
1 parent 362b6d3 commit f149d74
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/lru-cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,10 @@ Object.defineProperty(LRUCache.prototype, "itemCount",

LRUCache.prototype.forEach = function (fn, thisp) {
thisp = thisp || this
var i = 0;
for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) {
var i = 0
var itemCount = this._itemCount

for (var k = this._mru - 1; k >= 0 && i < itemCount; k--) if (this._lruList[k]) {
i++
var hit = this._lruList[k]
if (this._maxAge && (Date.now() - hit.now > this._maxAge)) {
Expand Down
37 changes: 37 additions & 0 deletions test/foreach.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,40 @@ test('keys() and values()', function (t) {

t.end()
})

test('all entries are iterated over', function(t) {
var l = new LRU(5)
for (var i = 0; i < 10; i ++) {
l.set(i.toString(), i.toString(2))
}

var i = 0
l.forEach(function (val, key, cache) {
if (i > 0) {
cache.del(key)
}
i += 1
})

t.equal(i, 5)
t.equal(l.keys().length, 1)

t.end()
})

test('all stale entries are removed', function(t) {
var l = new LRU({ max: 5, maxAge: -5, stale: true })
for (var i = 0; i < 10; i ++) {
l.set(i.toString(), i.toString(2))
}

var i = 0
l.forEach(function () {
i += 1
})

t.equal(i, 5)
t.equal(l.keys().length, 0)

t.end()
})

0 comments on commit f149d74

Please sign in to comment.