今天是学习前端的第391天,学习了一下在牛客看到同学的URLCatche缓存写的十分的有意思就研究了一下,并可以加强我们对指针的学习。
URLCatche大概含义就是个具有一定长度的储存卡,首先设置上长度size,存储put的长度超过限制后会将最开始存储的数据删除掉,获取get数据后数据会放到首位。
这是一个空URLCatche
![在这里插入图片描述](https://img-blog.csdnimg.cn/4cae05b2f2414bb69424724384786d1c.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L21tbW1tbW1tbW16,size_16,color_FFFFFF,t_70)
存入一条数据后
![在这里插入图片描述](https://img-blog.csdnimg.cn/af9758bea43c4333b8176f7493639255.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L21tbW1tbW1tbW16,size_16,color_FFFFFF,t_70)
使用
![在这里插入图片描述](https://img-blog.csdnimg.cn/55701783be864069b3ad12995ca0466d.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L21tbW1tbW1tbW16,size_16,color_FFFFFF,t_70)
源码放在下面:
class ListNode {
constructor(key, val) {
this.key = key
this.val = val
this.pre = null
this.next = null
}
}
var LRUCache = function (capacity) {
this.size = capacity
this.map = new Map()
this.head = new ListNode(null, null)
this.tail = new ListNode(null, null)
this.head.next = this.tail
this.tail.pre = this.head
}
LRUCache.prototype.get = function (key) {
if (!this.map.has(key)) return -1
const val = this.map.get(key).val
this.put(key, val)
return val
}
LRUCache.prototype.put = function (key, value) {
if (!this.map.has(key)) {
if (this.map.size === this.size) {
let node = this.tail.pre
const k = node.key
this.tail.pre = node.pre
node.pre.next = this.tail
node.pre = null
node.next = null
node = null
this.map.delete(k)
}
const node = new ListNode(key, value)
node.next = this.head.next
node.pre = this.head
node.next.pre = node
node.pre.next = node
this.map.set(key, node)
} else {
const node = this.map.get(key)
node.val = value
if (node.pre !== this.head) {
node.pre.next = node.next
node.next.pre = node.pre
node.pre = this.head
node.next = this.head.next
node.pre.next = node
node.next.pre = node
}
}
}
const cache = new LRUCache(2)
cache.put('a', 123)
cache.put('b', 456)
cache.put('c', 789)