-
-
Save ibolmo/755698 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
// A memoize function to store function results of heavy functions | |
(function(slice){ | |
Function.prototype.memoize = function(hashFn, bind){ | |
var cache = {}, self = bind ? this.bind(bind) : this, hashFn = hashFn || JSON.stringify; | |
return function(){ | |
return ((key = hashFn(slice.call(arguments))) in cache) ? cache[key] : (cache[key] = self(key)); | |
}; | |
}; | |
})(Array.prototype.slice); | |
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