/**
* lru
*/
class myLRU{
constructor(length){
this.length = length
this.map = new Map()
}
get(key){
if (this.map.has(key)) {
return this.map.get(key)
}
let value = this.map.delete(key)
this.map.set(key,value)
}
set(key,value){
if (this.map.has(key)) {
this.map.delete(key)
}
this.map.set(key,value)
if (this.map.size>this.length) {
let firstKey = this.map.keys().next().value
this.map.delete(firstKey)
}
}
}
let lru = new myLRU(4)
lru.set("a",1)
lru.set("b",2)
lru.set("c",3)
lru.set("d",4)
console.log(lru.get("a"))//1
console.log(lru.get("b"))//2
console.log(lru.get("c"))//3
console.log(lru.get("d"))//4
lru.set("e",5)
console.log(lru.get("a"))//undefined
console.log(lru.get("e"))//5
19 手写JavaScript LRU
最新推荐文章于 2024-06-14 15:02:13 发布