LRU 设计原则
LRU 缓存机制 应该支持以下操作 获取数据 get 和 修改数据put ,
获取数据 get(key) ,密钥 ( key ) 存在于缓存中,则获取密钥的值,更新key 到最新的位置,否则返回-1。写入数据 put(key, value) - 如果密钥不存在,则写入数据。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据,从而为新数据留出空间。
1.数组+Object
const LRUCache = function(capacity) {
this.keys = []
this.cache = Object.create(null)
this.capacity = capacity
};
LRUCache.prototype.get = function(key) {
if(this.cache[key]) {
// 调整位置
remove(this.keys, key)
this.keys.push(key)
return this.cache[key]
}
return -1
};
LRUCache.prototype.put = function(key, value) {
if(this.cache[key]) {
// 存在即更新
this.cache[key] = value
remove(this.keys, key)
this.keys.push(key)
} else {
// 不存在即加入
this.keys.push(key)
this.cache[key] = value
// 判断缓存是否已超过最大值
if(this.keys.length > this.capacity) {
removeCache(this.cache, this.keys, this.keys[0])
}
}
};
// 移除 key
function remove(arr, key) {
if (arr.length) {
const index = arr.indexOf(key)
if (index > -1) {
return arr.splice(index, 1)
}
}
}
// 移除缓存中 key
function removeCache(cache, keys, key) {
cache[key] = null
remove(keys, key)
}
2. Map
new Map 返回一个迭代器 (Iterator),通过next()按顺序遍历各值。
利用 Map 既能保存键值对,并且能够记住键的原始插入顺序
class LRUCache {
constructor(capacity: number) {
this.capacity = capacity;
this.caches = new Map();
}
get(key) {
if (this.cache.has(key)) {
// 存在即更新
let temp = this.caches.get(key);
this.caches.delete(key);
this.caches.set(key, temp);
return temp;
}
return -1;
}
set(key, value) {
if (this.caches.has(key)) {
// 存在即更新(删除后加入)
this.caches.delete(key);
} else if (this.caches.size >= this.capacity) {
// 不存在即加入
// 缓存超过最大值,则移除最近没有使用的
this.caches.delete(this.cache.keys().next().value);
}
this.caches.set(key, value);
}
}