timed-cache
Version:
A minimalist time-based caching system.
2 lines (1 loc) • 797 B
JavaScript
;const t=function(t){return"string"!=typeof t?"__cache__"+JSON.stringify(t):"__cache__"+t};module.exports=class{constructor(t={defaultTtl:6e4}){this.cache={},this.defaultTtl=t.defaultTtl||6e4}put(e,c,a){const h=(a?a.ttl:void 0)||this.defaultTtl,s=(a?a.callback:void 0)||function(){},l=t(e),i=this.cache[l];i&&clearTimeout(i.handle);const o=setTimeout((()=>this.remove(e)),h);this.cache[l]={handle:o,data:c,callback:s}}get(e){const c=this.cache[t(e)];return c&&c.data}remove(e){const c=t(e),a=this.cache[c];a&&(clearTimeout(a.handle),delete this.cache[c],a.callback(e,a.data))}clear(){for(const c in this.cache)t=this.cache,e=c,null!==t&&Object.prototype.hasOwnProperty.call(t,e)&&clearTimeout(this.cache[c].handle);var t,e;this.cache={}}size(){return Object.keys(this.cache).length}};