Created
December 26, 2010 15:48
-
-
Save arian/755485 to your computer and use it in GitHub Desktop.
Function.prototype.memoize
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
// A memoize function to store function results of heavy functions | |
Function.prototype.memoize = function(hashFn, bind){ | |
var memo = {}, | |
self = this; | |
if (!hashFn) hashFn = function(arg){ | |
return arg; | |
}; | |
return function(){ | |
var key = hashFn.apply(self, arguments); | |
return (key in memo) ? memo[key] : (memo[key] = self.apply(bind, arguments)); | |
}; | |
}; | |
var isPrime = function(num){ | |
var i = num - 2; | |
while (i--) if (num % (i + 2) == 0) return false; | |
console.log('Prime calculated of ' + num); | |
return true; | |
} | |
var isPrimeFast = isPrime.memoize(); | |
// Calculate the first primes twice | |
// since they will not change over time, we can use the memoized function | |
for (var i = 0; i < 1000; i++) if (isPrimeFast(i)) console.log('prime found: ' + i); | |
for (var i = 0; i < 1000; i++) if (isPrimeFast(i)) console.log('prime found again: ' + i); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment