Skip to content

Instantly share code, notes, and snippets.

@yanzhihong23
Last active September 24, 2020 08:25
Show Gist options
  • Save yanzhihong23/a1656d309cd112abe7317c483bc7f596 to your computer and use it in GitHub Desktop.
Save yanzhihong23/a1656d309cd112abe7317c483bc7f596 to your computer and use it in GitHub Desktop.
LRUCache
class LRUCache {
constructor(size) {
this.size = size;
this.cache = new Map();
}
put(key, value) {
const { cache, size } = this;
if(cache.has(key)) {
cache.delete(key);
} else if(cache.size >= size) {
cache.delete(cache.keys().next().value);
}
cache.set(key, value);
}
get(key) {
const { cache } = this;
if(cache.has(key)) {
const value = cache.get(key);
cache.delete(key);
cache.set(key, value);
return value;
}
return -1;
}
}
function LRUCache(size) {
this.size = size;
this.cache = new Map();
}
LRUCache.prototype.put = function(key, value) {
const { cache, size } = this;
if(cache.has(key)) {
cache.delete(key);
} else if(cache.size >= size) {
cache.delete(cache.keys().next().value);
}
cache.set(key, value);
};
LRUCache.prototype.get = function(key) {
const { cache } = this;
if(cache.has(key)) {
const value = cache.get(key);
cache.delete(key);
cache.set(key, value);
return value;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment