add: LRU缓存机制

This commit is contained in:
yige committed 2020-05-25 22:27:39 +08:00
1 parent 06d357b002
commit 3770b30040
3 files changed
+41

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
export default class LRUCache {
constructor (capacity) {
this.max = capacity; this.map = new Map()
}
get (key) {
const value = this.map.get(key)
if (value !== undefined) {
this.map.delete(key)
this.map.set(key, value)
return value
}
return -1
}
put (key, value) {
this.map.delete(key)
this.map.set(key, value)
if (this.map.size > this.max) this.map.delete(this.map.keys().next().value)
}
}