UNPKG

@stryke/helpers

Version:

A package containing miscellaneous helper functions that are used across many different Storm Software projects.

2 lines (1 loc) 1.37 kB
class r{key;data;size;prev=null;next=null;constructor(e,t,i){this.key=e,this.data=t,this.size=i}}class l{prev=null;next=null}export class LRUCache{cache=new Map;head;tail;totalSize=0;maxSize;calculateSize;constructor(e,t){this.maxSize=e,this.calculateSize=t,this.head=new l,this.tail=new l,this.head.next=this.tail,this.tail.prev=this.head}addToHead(e){e.prev=this.head,e.next=this.head.next,this.head.next.prev=e,this.head.next=e}removeNode(e){e.prev.next=e.next,e.next.prev=e.prev}moveToHead(e){this.removeNode(e),this.addToHead(e)}removeTail(){const e=this.tail.prev;return this.removeNode(e),e}set(e,t){const i=this.calculateSize?.(t)??1;if(i>this.maxSize)return;const a=this.cache.get(e);if(a)a.data=t,this.totalSize=this.totalSize-a.size+i,a.size=i,this.moveToHead(a);else{const s=new r(e,t,i);this.cache.set(e,s),this.addToHead(s),this.totalSize+=i}for(;this.totalSize>this.maxSize&&this.cache.size>0;){const s=this.removeTail();this.cache.delete(s.key),this.totalSize-=s.size}}has(e){return this.cache.has(e)}get(e){const t=this.cache.get(e);if(t)return this.moveToHead(t),t.data}*[Symbol.iterator](){let e=this.head.next;for(;e&&e!==this.tail;){const t=e;yield[t.key,t.data],e=e.next}}remove(e){const t=this.cache.get(e);t&&(this.removeNode(t),this.cache.delete(e),this.totalSize-=t.size)}get size(){return this.cache.size}get currentSize(){return this.totalSize}}