Skip to content

Instantly share code, notes, and snippets.

@tanem
Created March 4, 2011 01:13
Show Gist options
  • Save tanem/853963 to your computer and use it in GitHub Desktop.
Save tanem/853963 to your computer and use it in GitHub Desktop.
Function.prototype.cached = function(){
// grab the calling function
var originalFunction = this;
// add a cache attribute
originalFunction["cache"] = {};
return function() {
// no real smarts here, just grab the first arg for now
var arg = arguments[0];
// if there is no cached result for the parameter, calculate
// the value using the appropriate function and cache the result.
// logging statements + extra code left here so we can verify what's happening for
// the purposes of the exercise!
if (typeof originalFunction.cache[arg] === "undefined") {
console.log("About to cache the result of " + arg + " being passed to "
+ originalFunction.name);
originalFunction.cache[arg] = originalFunction(arg);
} else {
console.log("Retrieving the cached result of " + arg + " being passed to "
+ originalFunction.name);
}
// return the cached value (either pre-existing or just set from above)
return originalFunction.cache[arg];
};
}
// stripped down isPrime function
function isPrime(num) {
// everything but 1 can be prime
var prime = num != 1;
for ( var i = 2; i < num; i++ ) {
if ( num % i == 0 ) {
prime = false;
break;
}
}
return prime;
}
// some Math.sin examples
var cachedSin = Math.sin.cached();
console.log(cachedSin(1));
console.log(cachedSin(2));
console.log(cachedSin(1));
console.log(cachedSin(2));
// some isPrime examples
var cachedIsPrime = isPrime.cached();
console.log(cachedIsPrime(1));
console.log(cachedIsPrime(3));
console.log(cachedIsPrime(1));
console.log(cachedIsPrime(3));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment