class LRUCache {
length
data = new Map()
constructor(length) {
if(length < 1) throw new Error('error')
this.length = length
}
set(key, value) {
const data = this.data
if(data.has(key)) {
data.delete(key)
}
data.set(key, value)
//如果超出长度,删除第一个元素
if(data.size > this.length) {
const delKey = data.keys().next().value
data.delete(delKey)
}
}
get(key) {
const data = this.data
if(!data.has(key)) return null
const value = data.get(key)
//将获取的元素添加到末尾
data.delete(key)
data.set(key, value)
return value
}
}
const lruCache = new LRUCache(3)
lruCache.set('1', '1') //{1=1}
lruCache.set('2', '2') //{1=1, 2=2}
lruCache.set('3', '3') //{1=1, 2=2, 3=3}
lruCache.set('4', '4') //{2=2, 3=3, 4=4} 长度为3,删除最老的1=1
console.log(lruCache.get('2')) //{3=3, 4=4, 2=2} 重新获取了一次2,所以2排在最后面
JS实现LRU缓存
最新推荐文章于 2024-03-18 10:37:12 发布