Guest User

Untitled

a guest
Jan 22nd, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. // A more functional memoizer
  2.  
  3. //We can beef up our module by adding functions later
  4. var Memoizer = (function(){
  5. //Private data
  6. var cache = {};
  7. //named functions are awesome!
  8. function cacher(func){
  9. return function(){
  10. var key = JSON.stringify(arguments);
  11. if(cache[key]){
  12. return cache[key];
  13. }
  14. else{
  15. val = func.apply(this, arguments);
  16. cache[key] = val;
  17. return val;
  18. }
  19. }
  20. }
  21. //Public data
  22. return{
  23. memo: function(func){
  24. return cacher(func);
  25. }
  26. }
  27. })()
  28.  
  29.  
  30. var fib = Memoizer.memo(function(n){
  31. if (n < 2){
  32. return 1;
  33. }else{
  34. return fib(n-2) + fib(n-1);
  35. }
  36. });
Add Comment
Please, Sign In to add comment