Skip to content

Instantly share code, notes, and snippets.

@dhigginbotham
Created April 4, 2017 00:04
Show Gist options
  • Save dhigginbotham/bdb20a3e778ff52c26353d9aeb2cd053 to your computer and use it in GitHub Desktop.
Save dhigginbotham/bdb20a3e778ff52c26353d9aeb2cd053 to your computer and use it in GitHub Desktop.
const store = {
cache: {},
expires: 0,
ttl: '1h'
};
function cacheable(settings) {
return function cache() {
const now = Date.now();
let isExpired = false;
const cacheSize = Array.isArray(settings.cache)
? settings.cache.length
: Object.keys(settings.cache).length;
if (now >= settings.expires || cacheSize === 0) isExpired = true;
if (isExpired) {
settings.expires = now + ms(settings.ttl);
settings.cache = Array.isArray(settings.cache) ? [] : {};
}
log('statsCache:cacheSize:%d:expiresInMins:%s',
cacheSize,
`${Math.round((settings.expires - now) / 60000)}`);
return isExpired;
};
}
const expired = cacheable(store);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment