Skip to content

Instantly share code, notes, and snippets.

@meagar
Created September 8, 2011 20:47
Show Gist options
  • Save meagar/1204660 to your computer and use it in GitHub Desktop.
Save meagar/1204660 to your computer and use it in GitHub Desktop.
Exercise 07 - add closure
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;
}
}
return prime;
}
var cachify = function (fn) {
var cache = {};
return ((function(fn, cache) {
return function (arg) {
if (arg in cache) {
console.info('cache hit');
return cache[arg];
}
return cache[arg] = fn(arg);
};
})(fn, cache));
};
var isPrime = cachify(isPrime);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment