Advertisement
alexioak

lru_cache_impl.js

Jul 1st, 2015
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function LRUCache(capacity, init)
  2. {
  3.   var capacity = capacity;
  4.   var data = init || {};
  5.   var timestamps = {};
  6.  
  7.   var getTimestamp = function()
  8.   {
  9.     var time = Date.now();
  10.    
  11.     while(time === Date.now());
  12.     return Date.now();
  13.   };
  14.  
  15.   var findLRU = function()
  16.   {
  17.     var keys = Object.keys(timestamps);
  18.    
  19.     return keys
  20.       .reduce(function(acc, x)
  21.       {
  22.         if (timestamps[x] < acc.time)
  23.         {
  24.           return {key: x, time: timestamps[x]} ;
  25.         } else { return acc;}
  26.     }, {key: keys[0], time: timestamps[keys[0]] });
  27.   };
  28.  
  29.   var cache = function(key, val)
  30.   {
  31.     if (!key) return data;
  32.     if (key && val)
  33.     {
  34.       setCache(key, val);
  35.     }
  36.    
  37.     if (this.size > this.capacity)
  38.     {
  39.       var lruItem = findLRU();
  40.       deleteCache(lruItem.key);
  41.     }
  42.        
  43.     return this;
  44.   }.bind(this);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement