Created
December 19, 2012 06:50
-
-
Save campaul/4334915 to your computer and use it in GitHub Desktop.
A concise JavaScript LRU cache.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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