Skip to content

Instantly share code, notes, and snippets.

@codekipple
Created March 4, 2011 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codekipple/855301 to your computer and use it in GitHub Desktop.
Save codekipple/855301 to your computer and use it in GitHub Desktop.
javascript master class with Amy Hoy and Thomas Fuchs: Homework part 1
// Part 1.
// Implement a function prototype extension that caches function results for
// the same input arguments of a function with one parameter.
//
// For example:
// Make sin(1) have the result of Math.sin(1), but use a cached value
// for future calls.
//
// Part 2.
// Use this new function to refactor the code example.
// Some good test numbers: 524287, 9369319, 2147483647 (all primes)
Function.prototype.cached = function( num, method ){
if( this.cache == null ){
this.cache = {};
}
if( this.cache[ num ] != null ){
return this.cache[ num ];
}else{
var result = method( num );
this.cache[ num ] = result + '(cache hit)';
return result;
}
}
function cachedSin( num ) {
return cachedSin.cached( num, function( num ){
// everything but 1 can be prime
var sin = Math.sin(num);
return sin;
});
};
function isPrime( num ) {
return isPrime.cached( num, function( 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;
});
};
console.log( isPrime(524287) );
console.log( isPrime(524287) );
console.log( cachedSin(1) );
console.log( cachedSin(1) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment