LRUCache

 avatar
unknown
javascript
3 years ago
2.2 kB
7
Indexable
/*
  Applicant: Vinicius Gamaliel
  Implements a LRU cache in javascript
   LRU ( least recently used)
   - Should be able to insert
   - Should be able to get
   - Should be able to update the cache when getting a item
   - Cant have more the 10 elements
   size: 10 elements */


const MAX_SIZE = 10;

class LRUCache {
     queue = [];
     hashmap = {}

    insert (key,object) {

        const size = this.queue.push(object)
        this.hashmap[key] = size -1;
        if(size >MAX_SIZE ){
            this.popLastItem();
        }
    } 

    get(key){ 
        this.updateFirstItem(key);
        console.log('quere',':', this.queue)
        return this.queue[this.hashmap[key]]
    };

    updateFirstItem(key){
        const object = this.queue[this.hashmap[key]];
        if(object){
            this.queue.splice(this.hashmap[key],1)
            const pos = this.queue.push(object) -1
            Object.keys(this.hashmap).forEach((k) =>{ 
            if( k == key){ 
                this.hashmap[k]=pos;
                return;
            }
            this.hashmap[k] = this.hashmap[k] -1;
        });   
        }
        
    }
    
    popLastItem(){
        this.queue.splice(0,1)  
  
        Object.keys(this.hashmap).forEach((key) =>{ 
            if( this.hashmap[key]==0 ){ 
                delete this.hashmap[key];
                return;
            }

            this.hashmap[key] = this.hashmap[key] -1;
        });

    }
}

const lruCache = new LRUCache();

lruCache.insert('request1', {'test': 'object1'})

console.log('request1',lruCache.get('request1'))
console.log('request2',lruCache.get('request2'))

lruCache.insert('request3', {'test': 'object3'})
lruCache.insert('request4', {'test': 'object4'})
lruCache.insert('request5', {'test': 'object5'})
lruCache.insert('request6', {'test': 'object6'})
lruCache.insert('request7', {'test': 'object7'})



lruCache.insert('request8', {'test': 'object8'})
lruCache.insert('request9', {'test': 'object9'})
lruCache.insert('request10', {'test': 'object10'})
lruCache.insert('request11', {'test': 'object11'})



console.log(lruCache.get('request6'))
console.log(lruCache.get('request3'))
console.log(lruCache.get('request3232'))




Editor is loading...