Created
November 18, 2012 09:01
-
-
Save ptquang86/4104305 to your computer and use it in GitHub Desktop.
Javascript - Cache function result
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
// 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