Design LRUCache in TypeScript

--

Photo by Chris Ried on Unsplash

Least Recently Used Cache — LRU Cache

  1. Discards/Evicts least-recently-accessed items first. LRU cache enusre that most relevant data remains available in the cache.
  2. It operates on the principle that most recently accessed data is likely to accessed again in near future.

Various languages support LRU cache implementation.

But, You may asked in interview to implement your own LRU cache.

Following code is implement in TypeScript. But, you can implement that in any programming language.

TypeScript Code

class LRUCache<T,K>{
cache;
capacity;

constructor(capacity:number){
this.cache = new Map();
this.capacity = capacity;
}

// Implementing Get Method
get(key:T){
if(!this.cache.has(key)) return -1;

let val = this.cache.has(key);
this.cache.delete(key);
this.cache.set(key,val);
return val;

}

put(key:T,value:K){
this.cache.delete(key);

if(this.cache.size===this.capacity){
// delete the least recently accessed
// const key = Array.from(this.cache.keys())[0];
// this.cache.delete(key) or
this.cache.delete(this.cache.keys().next().value);
this.cache.set(key,value);
}else{
this.cache.set(key,value);
}

}

getLeastRecent(){
return Array.from(this.cache)[0];
}

getMostRecent(){
return Array.from(this.cache)[this.cache.size-1];
}
}

const obj = new LRUCache(5);

console.log(obj.put('first',{'name':'alok'}));
console.log(obj.put('second',2));
console.log(obj.put('third',3));
console.log(obj.put('first',{'name':'alok'}));

console.log(obj.getLeastRecent());
console.log(obj.getMostRecent());

Resources

  1. https://dev.to/seanwelshbrown/implement-a-simple-lru-cache-in-javascript-4o92
  2. https://redis.io/glossary/lru-cache/https://www.baeldung.com/java-lru-cache
  3. https://en.wikipedia.org/wiki/Cache_replacement_policies
  4. https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU
  5. https://www.enjoyalgorithms.com/blog/implement-least-recently-used-cache
  6. https://www.interviewcake.com/concept/java/lru-cache
  7. https://leetcode.com/problems/lru-cache/description/

--

--