Last active
December 29, 2015 10:39
-
-
Save chiral/7657978 to your computer and use it in GitHub Desktop.
simple general cache function.
This file contains 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 stats = { | |
hit: 0, miss: 0 | |
}; | |
exports.LRU = function(size,k_match) { | |
var tbl=[]; | |
if (!k_match) k_match=function(k1,k2) { | |
if (k1.length!=k2.length) | |
return false; | |
for (var i=0; i<k1.length; i++) | |
if (k1[i]!==k2[i]) return false; | |
return true; | |
} | |
return function() { | |
var k=[]; | |
k.push.apply(k,arguments); | |
var f=k.shift(); | |
for (var i=tbl.length-1; i>=0; i--) { | |
var r=tbl[i]; | |
if (r.f===f && k_match(r.k,k)) { | |
while (i<tbl.length-1) { | |
tbl[i]=tbl[i+1]; i++; | |
} | |
tbl[tbl.length-1]=r; | |
stats.hit++; | |
return r.v; | |
} | |
} | |
var v=f.apply(null,k); | |
if (tbl.length>=size) tbl.shift(); | |
tbl.push({f:f,k:k,v:v}); | |
stats.miss++; | |
return v; | |
}; | |
}; | |
exports.stats = stats; | |
/* | |
general cache function. | |
Usage: | |
var cache = require('./cache.js'); | |
var cached = cache.LRU(100); // 100 LRU entries. | |
... | |
// you can substitute "some_func(arg1,arg2)" for below. | |
var result = cached(some_func,arg1,arg2); | |
Note: | |
while you can put different types of functions | |
(i.e. number of arguments) into a same cache, | |
it's recommended to separate caches by function types | |
as long as space issues are not concerned. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment