Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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);
Add Comment
Please, Sign In to add comment