Created
January 21, 2011 15:12
-
-
Save themartorana/789802 to your computer and use it in GitHub Desktop.
Caching Wrapper.js
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
// Part 1. | |
// Implement a function prototype extension that caches function results for | |
// the same input arguments of a function with one parameter. | |
// | |
// For example: | |
// Make sin(1) have the result of Math.sin(1), but use a cached value | |
// for future calls. | |
// | |
// Part 2. | |
// Use this new function to refactor the code example. | |
// Some good test numbers: 524287, 9369319, 2147483647 (all primes) | |
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; | |
} | |
Function.prototype.makeCacheable = function() { | |
originalMethod = this; | |
if (!('cache' in originalMethod)) { | |
originalMethod.cache = {} | |
} | |
return function(arg) { | |
if (arg in originalMethod.cache) { | |
console.log('cached'); | |
} | |
else { | |
console.log('not cached'); | |
originalMethod.cache[arg] = originalMethod(arg); | |
} | |
return originalMethod.cache[arg]; | |
} | |
}; | |
console.log(isPrime(524287)); | |
console.log(isPrime(9369319)); | |
console.log(isPrime(2147483647)); | |
isPrime = isPrime.makeCacheable(); | |
console.log(isPrime(524287)); | |
console.log(isPrime(9369319)); | |
console.log(isPrime(2147483647)); | |
console.log(isPrime(524287)); | |
console.log(isPrime(9369319)); | |
console.log(isPrime(2147483647)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment