Created
March 25, 2012 06:44
-
-
Save kaizhu256/2191915 to your computer and use it in GitHub Desktop.
nodejs - key/value cache with efficient lru flush algorithm
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
my.Cache = function(ll) { | |
this.l1 = {}; this.l2 = {}; this.ii = 0; this.ll = ll || 256; | |
}; | |
my.Cache.prototype = { | |
'flush': function() {this.l1 = {}; this.l2 = {}; this.ii = 0;}, | |
'get': function(kk, vv0) { | |
this.ii += 1; | |
return this.l1[kk] === undefined ? this.l1[kk] = vv0 : this.l2[kk] = this.l1[kk]; | |
}, | |
'set': function(kk, vv) { | |
//// flush cache if counter ii > ll | |
if((this.ii += 1) > this.ll) {this.l1 = this.l2; this.l2 = {}; this.ii = 0;} | |
this.l1[kk] = this.l2[kk] = vv; | |
//// return true if cache will be flushed on next write | |
//// giving caller the opportunity to backup data | |
return this.ii >= this.ll; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment