Permalink
Browse files

add 'evict' event

  • Loading branch information...
dustyleary committed Apr 17, 2012
1 parent ac87842 commit c504d4969e3e5d17fca1a9a7ad3757ba68147933
Showing with 26 additions and 1 deletion.
  1. +8 −1 index.js
  2. +18 −0 test/lru-test.js
View
@@ -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];
@@ -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});
};
View
@@ -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.