Skip to content

Instantly share code, notes, and snippets.

@cameronism
Created March 4, 2011 06:40
Show Gist options
  • Save cameronism/854274 to your computer and use it in GitHub Desktop.
Save cameronism/854274 to your computer and use it in GitHub Desktop.
// Part 1.
// Implement a function prototype extension that caches function results for
// the same input arguments of a function with one parameter.
Function.prototype.cached = function() {
var cache = {},
func = this;
return function( arg ) {
return cache[ arg ] = arg in cache ? cache[ arg ] : func(arg);
};
};
// Part 2.
// Use this new function to refactor the code example.
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;
}
}
console.log('prime it');
return prime;
}
var cachedIsPrime = isPrime.cached();
cachedIsPrime(11);
cachedIsPrime(11);
var cachedSin = function( num ) {
console.log('sine it');
return Math.sin(num);
}.cached();
cachedSin(1);
cachedSin(1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment