Last active
December 29, 2015 10:39
-
-
Save chiral/7658278 to your computer and use it in GitHub Desktop.
another version of general cache "https://gist.github.com/chiral/7657978" which supports "this" object for callee
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 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(); | |
| var t=k.shift(); | |
| for (var i=tbl.length-1; i>=0; i--) { | |
| var r=tbl[i]; | |
| if (r.f===f && r.t===t && 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(t,k); | |
| if (tbl.length>=size) tbl.shift(); | |
| tbl.push({f:f,t:t,k:k,v:v}); | |
| stats.miss++; | |
| return v; | |
| }; | |
| }; | |
| exports.stats = stats; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment