With that, we can initialize doubly linked list
nodes easily by calling new DLinkedNode(key, value, null, null)
.
In the Cache
class, we'll also want to add the standard addNode
and removeNode
helper methods, as we'll be doing that quite a bit. addNode
specifically adds a new node to the head of the doubly linked list. removeNode
removes it place by manipulating the pre
and next
values of its neighbors.
1class DLinkedNode {
2 constructor(key, val, pre, next) {
3 this.key = key;
4 this.val = val;
5 this.pre = pre;
6 this.next = next;
7 }
8}
9
10// for our Cache class
11addNode(node) {
12 node.pre = this.head;
13 node.next = this.head.next;
14 this.head.next.pre = node;
15 this.head.next = node;
16};
17
18removeNode(node) {
19 // take a node's predecessor
20 const pre = node.pre;
21 // find the node after it
22 const next = node.next;
23 // assign the predecessor's "next" node as the one after current
24 pre.next = next;
25 next.pre = pre;
26};