Created
October 20, 2010 16:05
-
-
Save madrobby/636709 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); |
(from our JavaScript Master Class!)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
memoize sugar +1