Skip to content

Instantly share code, notes, and snippets.

@hglattergotz
Created November 11, 2011 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hglattergotz/1358220 to your computer and use it in GitHub Desktop.
Save hglattergotz/1358220 to your computer and use it in GitHub Desktop.
Homework Exercise 7 part 2
// Part 2.
// Use this new function to refactor the code example.
// Some good test numbers: 524287, 9369319, 2147483647 (all primes)
//
// In other words, if you have this code:
//
// Function.prototype.cached = function(){
// ? (what goes here?)
// }
//
// // For the isPrime function
//
// var cachedIsPrime = isPrime.cached();
// isPrime(11); // --> true (cache miss, calls original isPrime(1) function, stores return value in cache)
// isPrime(11); // --> true (cache hit, directly returns value)
//
// // ..but it short work on anything that takes just one (numeric) argument:
//
// var cachedSin = Math.sin.cached();
//
// cachedSin(1); // --> 0.8414709848078965 (cache miss, calls original Math.sin(1) function, stores return value in cache)
// cachedSin(1); // --> 0.8414709848078965 (cache hit, directly returns value)
Function.prototype.cached = function() {
var cache = {}, extendedFunction = this;
// Non logging version
//return function(val) {
// return cache[val] = (val in cache) ? cache[val] : extendedFunction(val);
//};
return function(val) {
if (val in cache) {
console.log('cache hit');
} else {
console.log('cache miss');
cache[val] = extendedFunction(val);
}
return cache[val];
}
}
function isPrime(num) {
var prime = num != 1;
for (var i = 2; i < num; i++) {
if (num % i == 0) {
prime = false;
break;
}
}
return prime;
}
var isPrimeCached = isPrime.cached();
console.log(isPrimeCached(524287));
console.log(isPrimeCached(9369319));
console.log(isPrimeCached(524287));
console.log(isPrimeCached(9369319));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment