Skip to content

Instantly share code, notes, and snippets.

@mamuso
Created July 29, 2010 23:46
Show Gist options
  • Save mamuso/499533 to your computer and use it in GitHub Desktop.
Save mamuso/499533 to your computer and use it in GitHub Desktop.
// Para rectificar con http://gist.github.com/500794
// 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.
//
Object.extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
};
Object.extend(Function.prototype, {
cache: function(k, v) {
if (!this.cache[k]) {
this.cache[k] = v;
}
return this.cache[k];
}
});
var sin = function(num) {
return sin.cache[num] || sin.cache(num, Math.sin(num));
};
// Part 2.
// Use this new function to refactor the code example.
// Some good test numbers: 524287, 9369319, 2147483647 (all primes)
function isPrime(num) {
return isPrime.cache[num] ||
isPrime.cache(num, function(num){
// everything but 1 can be prime
var prime = num != 1,
i = 2;
while ( i < num ) {
if ( num % i++ === 0 ) {
prime = false;
break;
}
}
return prime;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment