一句话:淘汰不活跃的值,如果都不活跃先淘汰前面的
typescript
class LRUCache {
capacity: number // 容量
cache: Map<any, any>
order: any[]
constructor(capacity: number) {
this.capacity = capacity
this.cache = new Map()
this.order = []
}
get(key: any) {
if (this.cache.has(key)) {
const value = this.cache.get(key)
this.updateOrder(key)
return value
} else {
return null
}
}
set(key: any, value: any) {
if (this.cache.has(key)) {
// 说明值存过了
this.cache.set(key)
this.updateOrder(key)
} else {
this.cache.set(key)
this.order.push(key)
// 如果超出容量
if (this.order.length > this.capacity) {
const oldKey = this.order.shift()
this.cache.delete(oldKey)
}
}
}
updateOrder(key: any) {
const index = this.order.indexOf(key)
this.order.splice(index, 1)
this.order.push(key)
}
}
const lru = new LRUCache(3)