| 111 | } |
| 112 | |
| 113 | remove(url: string): boolean { |
| 114 | const node = this.state.map[url]; |
| 115 | if (node === undefined) { |
| 116 | return false; |
| 117 | } |
| 118 | |
| 119 | // Special case if removing the current head. |
| 120 | if (this.state.head === url) { |
| 121 | // The node is the current head. Special case the removal. |
| 122 | if (node.next === null) { |
| 123 | // This is the only node. Reset the cache to be empty. |
| 124 | this.state.head = null; |
| 125 | this.state.tail = null; |
| 126 | this.state.map = {}; |
| 127 | this.state.count = 0; |
| 128 | return true; |
| 129 | } |
| 130 | |
| 131 | // There is at least one other node. Make the next node the new head. |
| 132 | const next = this.state.map[node.next!]!; |
| 133 | next.previous = null; |
| 134 | this.state.head = next.url; |
| 135 | node.next = null; |
| 136 | delete this.state.map[url]; |
| 137 | this.state.count--; |
| 138 | return true; |
| 139 | } |
| 140 | |
| 141 | // The node is not the head, so it has a previous. It may or may not be the tail. |
| 142 | // If it is not, then it has a next. First, grab the previous node. |
| 143 | const previous = this.state.map[node.previous!]!; |
| 144 | |
| 145 | // Fix the forward pointer to skip over node and go directly to node.next. |
| 146 | previous.next = node.next; |
| 147 | |
| 148 | // node.next may or may not be set. If it is, fix the back pointer to skip over node. |
| 149 | // If it's not set, then this node happened to be the tail, and the tail needs to be |
| 150 | // updated to point to the previous node (removing the tail). |
| 151 | if (node.next !== null) { |
| 152 | // There is a next node, fix its back pointer to skip this node. |
| 153 | this.state.map[node.next]!.previous = node.previous!; |
| 154 | } else { |
| 155 | // There is no next node - the accessed node must be the tail. Move the tail pointer. |
| 156 | this.state.tail = node.previous!; |
| 157 | } |
| 158 | |
| 159 | node.next = null; |
| 160 | node.previous = null; |
| 161 | delete this.state.map[url]; |
| 162 | // Count the removal. |
| 163 | this.state.count--; |
| 164 | |
| 165 | return true; |
| 166 | } |
| 167 | |
| 168 | accessed(url: string): void { |
| 169 | // When a URL is accessed, its node needs to be moved to the head of the chain. |