Skip to content

Instantly share code, notes, and snippets.

@campaul
Created December 19, 2012 06:50
Show Gist options
  • Save campaul/4334915 to your computer and use it in GitHub Desktop.
Save campaul/4334915 to your computer and use it in GitHub Desktop.
A concise JavaScript LRU cache.
this.cache = (function() {
// Inserts a node into a circular double linked list
var insert = function(head, node) {
return (((node.prev = head.prev).next = node).next = head).prev = node;
};
// Removes a node from a circular double linked list
var remove = function(node) {
return ((node.prev.next = node.next).prev = node.prev) && node;
};
return function(source, lines) {
var index = {}, cache = (function() {
this.next = this.prev = this;
})();
return function(key) {
if(index.hasOwnProperty(key)) {
cache = insert(cache, remove(index[key]));
} else {
cache = index[key] = insert(cache, {
key: key, value: source(key)
});
// Remove the oldest element if the cache is full
lines - 1 ? lines -- : delete index[remove(cache.prev).key];
}
return cache;
};
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment