diff --git a/lib/simple_lru.js b/lib/simple_lru.js index 82787b9..f47eaf7 100644 --- a/lib/simple_lru.js +++ b/lib/simple_lru.js @@ -4,11 +4,12 @@ * LRU cache based on a double linked list */ -function ListElement(before,next,key,value){ +function ListElement(before,next,time,key,value){ this.before = before this.next = next this.key = key this.value = value + this.time = time } ListElement.prototype.setKey = function(key){ @@ -19,11 +20,11 @@ ListElement.prototype.setValue = function(value){ this.value = value } - function Cache(options){ if(!options) options = {} this.maxSize = options.maxSize + this.maxTime = options.maxTime this.reset() } @@ -43,10 +44,12 @@ Cache.prototype.get = function(key,hit){ * it to the head of linked list */ hit = hit != undefined && hit != null ? hit : true; - if(cacheVal && hit) + + if(cacheVal && hit && (!cacheVal.time || (Date.now() - cacheVal.time) < this.maxTime)) this.hit(cacheVal) - else + else return undefined + return cacheVal.value } @@ -61,7 +64,11 @@ Cache.prototype.set = function(key,val,hit){ if(actual){ actual.value = val - if(hit) this.hit(actual) + if(hit) + { + this.hit(actual) + actual.time = this.maxTime ? Date.now() : undefined + } }else{ var cacheVal if(this.size >= this.maxSize){ @@ -85,7 +92,7 @@ Cache.prototype.set = function(key,val,hit){ cacheVal.setValue(val) } - cacheVal = cacheVal ? cacheVal : new ListElement(undefined,undefined,key,val) + cacheVal = cacheVal ? cacheVal : new ListElement(undefined,undefined, this.maxTime ? Date.now() : undefined, key, val) this.cache[key] = cacheVal this.attach(cacheVal) } diff --git a/test/simple_lru_tests.js b/test/simple_lru_tests.js index 1229e05..a5bd695 100644 --- a/test/simple_lru_tests.js +++ b/test/simple_lru_tests.js @@ -59,4 +59,41 @@ describe("BigCache Config",function(){ for(var i = 0; i < 100; i++) cache.get(i).should.equal("value_"+i+"_modif") }) + + it("Should not return timeout item", function(done){ + var cache = new SimpleCache({maxSize:1, maxTime: 1}) + cache.set("hello", "world") + setTimeout(function() + { + should.equal(cache.get("hello"), undefined); + done(); + }, 10); + }) + + it("Should return timeout item", function(done){ + var cache = new SimpleCache({maxSize:1, maxTime:100}) + cache.set("hello", "world") + setTimeout(function() + { + should.equal(cache.get("hello"), "world") + done(); + }, 10); + }) + + it("Should set timestamp when you use Cache.set", function(done){ + var cache = new SimpleCache({maxSize:1, maxTime:100}) + cache.set("hello", "world") + setTimeout(function() + { + should.equal(cache.get("hello"), "world") + cache.set("hello", "world again") + setTimeout(function() + { + should.equal(cache.get("hello"), "world again"); + done(); + }, 75); + }, 75); + }) + + })