Skip to content

Commit

Permalink
Merge pull request #288 from null-a/lru-cache
Browse files Browse the repository at this point in the history
Back cache helper with LRU cache.
  • Loading branch information
stuhlmueller committed Jan 18, 2016
2 parents 49bf7d0 + e6e6f88 commit e87212c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"esutils": "^2.0.2",
"git-rev-2": "^0.1.0",
"immutable": "^3.7.5",
"lru-cache": "^4.0.0",
"minimist": "^1.2.0",
"numeric": "^1.2.6",
"priorityqueuejs": "~1.0.0",
Expand Down
21 changes: 13 additions & 8 deletions src/headerUtils.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

var serialize = require('./util').serialize
var LRU = require('lru-cache');

module.exports = function(env) {

Expand All @@ -13,25 +14,29 @@ module.exports = function(env) {
// Caution: if f isn't deterministic weird stuff can happen, since
// caching is across all uses of f, even in different execuation
// paths.
function cache(s, k, a, f) {
var c = {};
function cache(s, k, a, f, maxSize) {
var c = LRU(maxSize);
var cf = function(s, k, a) {
var args = Array.prototype.slice.call(arguments, 3);
var stringedArgs = serialize(args);
if (stringedArgs in c) {
return k(s, c[stringedArgs]);
if (c.has(stringedArgs)) {
return k(s, c.get(stringedArgs));
} else {
var newk = function(s, r) {
if (stringedArgs in c) {
if (c.has(stringedArgs)) {
// This can happen when cache is used on recursive functions
console.log('Already in cache:', stringedArgs);
if (serialize(c[stringedArgs]) !== serialize(r)) {
if (serialize(c.get(stringedArgs)) !== serialize(r)) {
console.log('OLD AND NEW CACHE VALUE DIFFER!');
console.log('Old value:', c[stringedArgs]);
console.log('Old value:', c.get(stringedArgs));
console.log('New value:', r);
}
}
c[stringedArgs] = r;
c.set(stringedArgs, r);
if (!maxSize && c.length === 1e4) {
console.log(c.length + ' function calls have been cached.');
console.log('The size of the cache can be limited by calling cache(f, maxSize).');
}
return k(s, r);
};
return f.apply(this, [s, newk, a].concat(args));
Expand Down

0 comments on commit e87212c

Please sign in to comment.