Created
May 21, 2010 20:10
-
-
Save devinus/409353 to your computer and use it in GitHub Desktop.
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
var LRUCache = function (maxsize) { | |
this._keys = []; | |
this._items = {}; | |
this._expires = {}; | |
this._size = 0; | |
this._maxsize = maxsize || 1024; | |
if (this._maxsize < 2) { | |
throw new Error("max size must be > 2"); | |
} | |
}; | |
LRUCache.prototype = { | |
set: function (key, value, callback) { | |
var keys = this._keys, | |
items = this._items, | |
expires = this._expires, | |
size = this._size, | |
maxsize = this._maxsize; | |
if (size >= maxsize) { // make room | |
keys.sort(function (a, b) { | |
if (expires[a] > expires[b]) return -1; | |
if (expires[a] < expires[b]) return 1; | |
return 0; | |
}); | |
size--; | |
delete expires[keys[size]]; | |
delete items[keys[size]]; | |
} | |
keys[size] = key; | |
items[key] = value; | |
expires[key] = Date.now(); | |
size++; | |
this._keys = keys; | |
this._items = items; | |
this._expires = expires; | |
this._size = size; | |
if (callback) return callback(size); | |
}, | |
get: function (key, callback) { | |
var item = this._items[key]; | |
if (item) this._expires[key] = Date.now(); | |
if (callback) return callback(item); | |
return item; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment