Last active
September 24, 2020 08:25
-
-
Save yanzhihong23/a1656d309cd112abe7317c483bc7f596 to your computer and use it in GitHub Desktop.
LRUCache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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