LRU 即 Least Recently Used,最近最少使用算法,简单来说即是在固定存储大小为 max 的存储空间内,当存储空间已满的情况下再进行新的数据存储时会将最近最少使用的数据剔除掉。
;((win) => {
const list = []
const max = 5
const lru = (data) => {
const index = list.indexOf(data)
if (index > -1) {
// 先判断要访问的数据是否已经存在了,存在的话就先删掉再压入栈顶
list.splice(index, 1)
} else if (list.length === max) {
// 如果要访问的数据不存在,且空间已满,则先删掉栈底的数据,也即是最近最少使用的数据
list.shift()
}
list.push(data)
console.log('current list: ', list)
}
win.lru = lru
})(window)