add: LRU缓存机制

This commit is contained in:
2020-05-25 22:27:39 +08:00
parent 06d357b002
commit 3770b30040
3 changed files with 41 additions and 0 deletions

21
src/array/lru-cache.js Normal file
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)
}
}