Skip to content

Instantly share code, notes, and snippets.

@alexgb
Created July 30, 2010 15:56
Show Gist options
  • Save alexgb/500759 to your computer and use it in GitHub Desktop.
Save alexgb/500759 to your computer and use it in GitHub Desktop.
// 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.
Function.prototype.cached = function() {
var fn = this,
cache = [];
return function() {
var arg = arguments[0];
if (arg in cache) {
return cache[arg];
}
return (cache[arg] = fn(arg));
};
};
sin = Math.sin.cached();
sin(Math.PI/2);
// => 1
sin(Math.PI/2);
// => 1 (cached)
//
// Part 2.
// Use this new function to refactor the code example.
// Some good test numbers: 524287, 9369319, 2147483647 (all primes)
isPrime = function(num) {
var prime = num != 1;
for ( var i = 2; i < num; i++ ) {
if ( num % i == 0 ) {
prime = false;
break;
}
}
return prime;
}.cached();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment