Created
September 8, 2011 20:47
-
-
Save meagar/1204660 to your computer and use it in GitHub Desktop.
Exercise 07 - add closure
This file contains 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
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