Skip to content

Instantly share code, notes, and snippets.

@shajanjp
Created November 14, 2019 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shajanjp/6c0ed69bb96f0025381f508dfd658a9e to your computer and use it in GitHub Desktop.
Save shajanjp/6c0ed69bb96f0025381f508dfd658a9e to your computer and use it in GitHub Desktop.
function Cache(size) {
this.store = {};
this.size = size;
this.get = function(k){
this.store[k].d = Date.now();
return this.store[k].v;
};
this.put = function(k, v) {
let objKeys = Object.keys(this.store);
if(objKeys.length < this.size){
this.store[k] = { v, d: Date.now() };
} else {
let lrd = Date.now();
let lro;
for(let i in objKeys){
if(this.store[i] < lrd){
lro = i;
}
}
delete this.store[lro];
this.store[k] = { v, d: Date.now() };
}
};
this.all = function() {
return this.store;
}
}
cache = new Cache(2) // capacity = 2
cache.put(1, "1")
cache.put(2, "2")
console.log(cache.get(1)) // returns "1"
cache.put(3, "3") // evicts key 2, because the key 1 was retrieved
console.log(cache.get(2)) // returns null, because 2 was just evicted
cache.put(4, "4") // evicts key 1,
console.log(cache.get(1)) // returns null, because it was evicted earlier
console.log(cache.get(3)) // returns "3"
console.log(cache.get(4)) // returns "4"
console.log(cache.all());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment