Skip to content

Instantly share code, notes, and snippets.

@madrobby
Created October 20, 2010 16:05
Show Gist options
  • Save madrobby/636709 to your computer and use it in GitHub Desktop.
Save madrobby/636709 to your computer and use it in GitHub Desktop.
// Solution to Part 1.
Function.prototype.cached = function(){
var self = this, cache = {};
return function(arg){
if(arg in cache) return cache[arg];
return cache[arg] = self(arg);
}
}
// A tracing version:
Function.prototype.cached = function(){
var self = this, cache = {};
return function(arg){
if(arg in cache) {
console.log('Cache hit for '+arg);
return cache[arg];
} else {
console.log('Cache miss for '+arg);
return cache[arg] = self(arg);
}
}
}
// Solution to Part 2.
function isPrime(num) {
var prime = num != 1;
for ( var i = 2; i < num; i++ ) {
if ( num % i == 0 ) {
prime = false;
break;
}
}
return prime;
}
isPrime = isPrime.cached();
@jdalton
Copy link

jdalton commented Oct 20, 2010

memoize sugar +1

@madrobby
Copy link
Author

(from our JavaScript Master Class!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment