Skip to content

Instantly share code, notes, and snippets.

@ptquang86
Created November 18, 2012 09:01
Show Gist options
  • Save ptquang86/4104305 to your computer and use it in GitHub Desktop.
Save ptquang86/4104305 to your computer and use it in GitHub Desktop.
Javascript - Cache function result
// http://www.sitekickr.com/blog/?p=946&preview=true
function Cache() {
// create the cache object as a singleton (only one instance allowed)
if(typeof Cache.instance === 'undefined') {
Cache.instance = this;
}
var data = [ ]
// we'll abbreviate cacheAwareCall as caCall
this.caCall = function(functionName) {
var cacheCheck = this.load(functionName, this.caCall.arguments);
if (typeof cacheCheck !== 'undefined') {
return cacheCheck;
else {
var returnValue = window[functionName].apply(this, this.caCall.arguments)
this.save(functionName, this.caCall.arguments, returnValue);
return returnValue;
}
}
this.save = function(functionName, argumentObject, returnValue) {
// prepend item to cache
data.unshift({ fname: functionName, arguments: argumentObject, returnValue: returnValue });
}
this.load = function(functionName, argumentObject) {
for(entry in data) {
if(data[entry]['fname'] === functionName) {
// we have a match on the function name
// deepCompare is not implemented here, examples are throughout the web
if(deepCompare(argumentObject, data[entry]['arguments']) {
return data[entry]['returnValue'];
}
}
}
return undefined;
}
Subscribe
return Cache.instance;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment