UNPKG

timed-cache

Version:

A minimalist time-based caching system.

2 lines (1 loc) 791 B
const t=function(t){return"string"!=typeof t?"__cache__"+JSON.stringify(t):"__cache__"+t};class e{constructor(t={defaultTtl:6e4}){this.cache={},this.defaultTtl=t.defaultTtl||6e4}put(e,c,a){const h=(a?a.ttl:void 0)||this.defaultTtl,l=(a?a.callback:void 0)||function(){},s=t(e),i=this.cache[s];i&&clearTimeout(i.handle);const n=setTimeout((()=>this.remove(e)),h);this.cache[s]={handle:n,data:c,callback:l}}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}}export{e as default};