Created
July 30, 2010 15:56
-
-
Save alexgb/500759 to your computer and use it in GitHub Desktop.
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. | |
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