You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
1 line
1.5 KiB
1 line
1.5 KiB
class t{constructor(t=0,s=0){this.first=null,this.items=Object.create(null),this.last=null,this.max=t,this.size=0,this.ttl=s}has(t){return t in this.items}clear(){return this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this}delete(t){if(this.has(t)){const s=this.items[t];delete this.items[t],this.size--,null!==s.prev&&(s.prev.next=s.next),null!==s.next&&(s.next.prev=s.prev),this.first===s&&(this.first=s.next),this.last===s&&(this.last=s.prev)}return this}evict(){const t=this.first;return delete this.items[t.key],this.first=t.next,this.first.prev=null,this.size--,this}get(t){let s;if(this.has(t)){const e=this.items[t];this.ttl>0&&e.expiry<=(new Date).getTime()?this.delete(t):(s=e.value,this.set(t,s,!0))}return s}keys(){return Object.keys(this.items)}set(t,s,e=!1){let i;if(e||this.has(t)){if(i=this.items[t],i.value=s,!1===e&&(i.expiry=this.ttl>0?(new Date).getTime()+this.ttl:this.ttl),this.last!==i){const t=this.last,s=i.next,e=i.prev;this.first===i&&(this.first=i.next),i.next=null,i.prev=this.last,t.next=i,null!==e&&(e.next=s),null!==s&&(s.prev=e)}}else this.max>0&&this.size===this.max&&this.evict(),i=this.items[t]={expiry:this.ttl>0?(new Date).getTime()+this.ttl:this.ttl,key:t,prev:this.last,next:null,value:s},1==++this.size?this.first=i:this.last.next=i;return this.last=i,this}}export default function(s=1e3,e=0){if(isNaN(s)||s<0)throw new TypeError("Invalid max value");if(isNaN(e)||e<0)throw new TypeError("Invalid ttl value");return new t(s,e)} |