Skip to content

Instantly share code, notes, and snippets.

@MichaelDimitras
Created May 17, 2018 17:02
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 MichaelDimitras/0a6f8203550ee81c7353fc20bfb67687 to your computer and use it in GitHub Desktop.
Save MichaelDimitras/0a6f8203550ee81c7353fc20bfb67687 to your computer and use it in GitHub Desktop.
/**
* @param {number} capacity
*/
var LFUCache = function(capacity) {
this.capacity = capacity;
this.storage = {};
};
/**
* @param {number} key
* @return {number}
*/
LFUCache.prototype.get = function(key) {
if(this.storage[key]) {
this.storage[key][1] += 1;
this.storage[key][2] = new Date();
return this.storage[key][0];
} else {
return -1;
}
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LFUCache.prototype.put = function(key, value) {
if (Object.keys(this.storage).length === this.capacity) {
let minFreq = Infinity;
let minKeys = [];
for(let i = 0; i < Object.keys(this.storage).length; i++) {
if (this.storage[Object.keys(this.storage)[i][1]] < minFreq){
minKeys = [Object.keys(this.storage)[i]];
} else if (this.storage[Object.keys(this.storage)[i][1]] === minFreq) {
minKeys.push(Object.keys(this.storage)[i])
}
}
let leastRecentDate = new Date();
let leastRecentKey;
for(let j = 0; j < minKeys.length; j++) {
if(minKeys[j][2] < leastRecentDate) {
leastRecentDate = minKeys[j][2];
leastRecentKey = minKeys[j];
}
}
delete this.storage[leastRecentKey];
}
this.storage[key] = [value, 0, new Date()]
};
/**
* Your LFUCache object will be instantiated and called as such:
* var obj = Object.create(LFUCache).createNew(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment