Guest User

Untitled

a guest
Jul 18th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. // A memoize function to store function results of heavy functions
  2.  
  3. Function.prototype.memoize = function(hashFn, bind){
  4. var memo = {},
  5. self = this;
  6.  
  7. if (!hashFn) hashFn = function(arg){
  8. return arg;
  9. };
  10.  
  11. return function(){
  12. var key = hashFn.apply(self, arguments);
  13. return (key in memo) ? memo[key] : (memo[key] = self.apply(bind, arguments));
  14. };
  15. };
  16.  
  17. var isPrime = function(num){
  18. var i = num - 2;
  19. while (i--) if (num % (i + 2) == 0) return false;
  20. console.log('Prime calculated of ' + num);
  21. return true;
  22. }
  23.  
  24. var isPrimeFast = isPrime.memoize();
  25.  
  26. // Calculate the first primes twice
  27. // since they will not change over time, we can use the memoized function
  28. for (var i = 0; i < 1000; i++) if (isPrimeFast(i)) console.log('prime found: ' + i);
  29. for (var i = 0; i < 1000; i++) if (isPrimeFast(i)) console.log('prime found again: ' + i);
Add Comment
Please, Sign In to add comment