LRU Cache using a doubly linked list
Thanks to https://alaindefrance.wordpress.com/2014/10/05/lru-cache-implementation/
JavaScript
var Node = function (key, data) {
this.key = key;
this.data = data;
this.previous = null;
this.next = null;
};
/**
* @constructor
*/
var LRUCache = function (capacity) {
this.capacity = capacity;
this.map = {};
this.head = null;
this.tail = null;
};
/**
* @private
* @method _add
*/
LRUCache.prototype._add = function (node) {
node.previous = node.next = null;
// first item
if (this.head === null) {
this.head = node;
this.tail = node;
}
// adding to existing items
this.head.previous = node;
node.next = this.head;
this.head = node;
};
/**
* @private
* @method _remove
*/
LRUCache.prototype._remove = function (node) {
// empty cache
if (this.head === null || this.tail === null) {
return;
}
// only item in the cache
if (this.head === node && this.tail === node) {
this.head = this.tail = null;
return;
}
// remove from head
if (this.head === node) {
this.head.next.previous = null;
this.head = this.head.next;
return;
}
// remove from tail
if (this.tail === node) {
this.tail.previous.next = null;
this.tail = this.tail.previous;
return;
}
// remove from middle
node.previous.next = node.next;
node.next.previous = node.previous;
};
/**
* @private
* @method _moveFirst
*/
LRUCache.prototype._moveFirst = function (node) {
this._remove(node);
this._add(node);
};
/**
* @private
* @method _removeLast
*/
LRUCache.prototype._removeLast = function () {
this._remove(this.tail);
};
/**
* @param {number} key
* @returns {number}
*/
LRUCache.prototype.get = function (key) {
// Existing item
if (this.map[key] !== undefined) {
// Move to the first place
var node = this.map[key];
this._moveFirst(node);
// Return
return node;
}
// Not found
return -1;
};
/**
* @param {number} key
...