Skip to content

Instantly share code, notes, and snippets.

@kaizhu256
Created March 25, 2012 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaizhu256/2191915 to your computer and use it in GitHub Desktop.
Save kaizhu256/2191915 to your computer and use it in GitHub Desktop.
nodejs - key/value cache with efficient lru flush algorithm
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