1 module.exports = function(size) {
2 return new LruCache(size)
5 function LruCache(size) {
6 this.capacity = size | 0
7 this.map = Object.create(null)
8 this.list = new DoublyLinkedList()
11 LruCache.prototype.get = function(key) {
12 var node = this.map[key]
13 if (node == null) return undefined
18 LruCache.prototype.set = function(key, val) {
19 var node = this.map[key]
23 if (!this.capacity) this.prune()
24 if (!this.capacity) return false
25 node = new DoublyLinkedNode(key, val)
33 LruCache.prototype.used = function(node) {
34 this.list.moveToFront(node)
37 LruCache.prototype.prune = function() {
38 var node = this.list.pop()
40 delete this.map[node.key]
46 function DoublyLinkedList() {
51 DoublyLinkedList.prototype.moveToFront = function(node) {
52 if (this.firstNode == node) return
56 if (this.firstNode == null) {
63 node.next = this.firstNode
69 DoublyLinkedList.prototype.pop = function() {
70 var lastNode = this.lastNode
71 if (lastNode != null) {
77 DoublyLinkedList.prototype.remove = function(node) {
78 if (this.firstNode == node) {
79 this.firstNode = node.next
80 } else if (node.prev != null) {
81 node.prev.next = node.next
83 if (this.lastNode == node) {
84 this.lastNode = node.prev
85 } else if (node.next != null) {
86 node.next.prev = node.prev
91 function DoublyLinkedNode(key, val) {