Created
November 5, 2010 15:44
-
-
Save olegp/664315 to your computer and use it in GitHub Desktop.
ringo-cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export("Cache"); | |
function Cache() { | |
var self = this; | |
this.size = 0; | |
this.map = {}; | |
function wrap(f, name, period, that) { | |
return function () { | |
var t = new Date().getTime(); | |
var args = Array.prototype.slice.call(arguments); | |
var key = name + ":" + args.toJSON(); //TODO use hash instead of full JSON representation | |
var r; | |
var value = that.map[key]; | |
if(value) { | |
r = value.result; | |
if(t < value.expires) { | |
return r; | |
} | |
//log.info("Overwriting " + key); | |
} | |
try { | |
//log.info("Added " + key); | |
r = f.apply(this, arguments); | |
that.map[key] = { result: r, expires: t + period }; | |
if(!value) that.size ++; | |
//log.info(that.size()); | |
} catch(e) { | |
//log.info("catch " + key); | |
// if the underlying call fails, log the error | |
//log.info(e.toJSON()); | |
// if we have a cached value, hide the exception, otherwise throw it | |
if(!r) throw e; | |
} | |
return r; | |
}; | |
} | |
this.cache = function(p, name, period) { | |
if(p instanceof Function) | |
return wrap(p, name, period, this); | |
var prefix = name ? name + "." : ""; | |
for(var key in p) { | |
var value = p[key]; | |
if(value instanceof Function) { | |
p[key] = wrap(value, prefix + key, period, this); | |
} | |
} | |
return p; | |
} | |
this.purge = function() { | |
var t = new Date().getTime(); | |
for(var key in self.map) { | |
var value = self.map[key]; | |
if(t > value.expires) { | |
//log.info("purged " + key); | |
delete self.map[key]; | |
self.size --; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment