Skip to content

Commit

Permalink
add 'evict' event
Browse files Browse the repository at this point in the history
  • Loading branch information
dustyleary committed Apr 17, 2012
1 parent ac87842 commit c504d49
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
9 changes: 8 additions & 1 deletion index.js
@@ -1,9 +1,14 @@
var events = require('events');
var sys = require('sys');

var LRU = exports.LRU = function (max) {
events.EventEmitter.call(this);
this.cache = {}
this.head = this.tail = null;
this.length = 0;
this.max = max || 1000;
};
sys.inherits(LRU, events.EventEmitter);

LRU.prototype.remove = function (key) {
var element = this.cache[key];
Expand Down Expand Up @@ -56,6 +61,8 @@ LRU.prototype.get = function (key) {

LRU.prototype.evict = function () {
if(!this.tail) { return; }
this.remove(this.tail);
var key = this.tail;
var element = this.remove(this.tail);
this.emit('evict', {key:key, value:element.value});
};

18 changes: 18 additions & 0 deletions test/lru-test.js
Expand Up @@ -123,5 +123,23 @@ suite.addBatch({
}
});

suite.addBatch({
"evict event": {
"'evict' event is fired when evicting old keys": function() {
var lru = new LRU.LRU(2);
var events = [];
lru.on('evict', function(element) { events.push(element); });

lru.set('foo1', 'bar1');
lru.set('foo2', 'bar2');
lru.set('foo3', 'bar3');
lru.set('foo4', 'bar4');

var expect = [{key:'foo1', value:'bar1'}, {key:'foo2', value:'bar2'}];
assert.deepEqual(events, expect);
}
}
});

suite.export(module);

0 comments on commit c504d49

Please sign in to comment.