Skip to content

Instantly share code, notes, and snippets.

@myndzi
Last active August 29, 2015 14:19
Show Gist options
  • Save myndzi/aa7563031db2c679f6e6 to your computer and use it in GitHub Desktop.
Save myndzi/aa7563031db2c679f6e6 to your computer and use it in GitHub Desktop.
'use strict';
var LRU = require('lru-cache');
function getArgs() {
var i = arguments.length, args = new Array(i);
while (i--) { args[i] = arguments[i]; }
return args;
}
module.exports = function (opts, fn) {
if (typeof opts === 'function') {
fn = opts;
opts = { };
} else {
opts = opts || { };
}
var cache = LRU(opts),
keyFn = (typeof opts.key === 'function' ? opts.key : JSON.stringify);
var len = parseInt(opts.length, 10);
if (isNaN(len)) { len = Infinity; }
var normalizeArgs = (typeof opts.normalize === 'function' ? opts.normalize : getArgs);
var cachified = function () {
var args = normalizeArgs.apply(this, arguments);
var cacheKey = keyFn(args.slice(0, Math.min(len, args.length)));
if (cache.has(cacheKey)) { return cache.get(cacheKey); }
var res;
// throw synchronously = don't store
res = fn.apply(this, args);
if (!res || typeof res !== 'object' || typeof res.then !== 'function') {
cache.set(cacheKey, res);
return res;
}
// wait for promise resolution
return res.then(function (value) {
// store successful promise -- not the value
cache.set(cacheKey, res);
return value;
});
// don't store rejected promise
};
// inherit cache methods
for (var key in cache) {
if (!/^_/.test(key) && typeof cache[key] === 'function') {
cachified[key] = cache[key].bind(cache);
}
}
return cachified;
};
@aredridel
Copy link

Why the slicing the args array?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment