Skip to content

Instantly share code, notes, and snippets.

@duskhacker
Created January 21, 2011 16:36
Show Gist options
  • Save duskhacker/789940 to your computer and use it in GitHub Desktop.
Save duskhacker/789940 to your computer and use it in GitHub Desktop.
// Daniel Z.'s solution
// 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 p(message){
console.log(message)
}
Function.prototype.cached = function() {
if (!('cache' in this )){
p("Setting up cache");
this.cache = {};
}
if ( this.cache[ arguments[0] ] != null ) {
p("From cache")
return this.cache[ arguments[0] ];
}
else {
return this.cache[arguments[0]] = arguments.callee.caller.compute(arguments[0])
}
}
function isPrime( num ) {
if ( result = isPrime.cached(num) != null )
return result;
}
isPrime.compute = function(num) {
p("From Computation")
// 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;
}
p(isPrime(524287))
p(isPrime(524287))
p(isPrime(9369319))
p(isPrime(9369319))
p(isPrime(2147483647))
p(isPrime(2147483647))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment