Created
January 21, 2011 16:32
-
-
Save GeertVL-zz/789932 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
<script> | |
// Part 1 | |
// Implement a function prototype extension that caches function results for | |
// the same input arguments of a function with one parameter. | |
Function.prototype.withCaching = function withCaching() { | |
if (!this.cache) { this.cache = {}; } | |
var method = this; | |
return function(input) { | |
if (typeof method.cache[input] == "undefined") { | |
var result = method.apply(this, [input]); | |
method.cache[input] = result; | |
} | |
return method.cache[input]; | |
}; | |
} | |
// Part 2 | |
// Use this new function to refactor the code example. | |
// Some good test numbers: 524287, 9369319, 2147483647 (all primes) | |
var isPrime = function(num) { | |
console.log("looking ..."); | |
var prime = num != 1; | |
// everything but 1 can be prime | |
for (var i = 2; i < num; i++) { | |
if (num % 1 == 0) { | |
prime = false; | |
break; | |
} | |
} | |
return prime; | |
}.withCaching(); | |
console.log(isPrime(4)); | |
console.log(isPrime(4)); | |
console.log(isPrime(524287)); | |
console.log(isPrime(524287)); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment