UNPKG

@andranik-arakelyan/js-utilities

Version:
1 lines 1.68 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.LRUCache=void 0;class LRUCache{capacity;cache;accessOrder;constructor(capacity){if(!Number.isInteger(capacity)||capacity<=0){throw new Error("Capacity must be a positive integer")}this.capacity=capacity;this.cache=new Map;this.accessOrder=[]}get(key){if(!this.cache.has(key)){return undefined}this.moveToEnd(key);return this.cache.get(key)}put(key,value){if(this.cache.has(key)){this.cache.set(key,value);this.moveToEnd(key);return}if(this.cache.size>=this.capacity){this.evictLeastRecentlyUsed()}this.cache.set(key,value);this.accessOrder.push(key)}has(key){return this.cache.has(key)}delete(key){if(!this.cache.has(key)){return false}this.cache.delete(key);const index=this.accessOrder.indexOf(key);if(index>-1){this.accessOrder.splice(index,1)}return true}clear(){this.cache.clear();this.accessOrder=[]}size(){return this.cache.size}getCapacity(){return this.capacity}isEmpty(){return this.cache.size===0}isFull(){return this.cache.size===this.capacity}keys(){return this.accessOrder[Symbol.iterator]()}*values(){for(const key of this.accessOrder){yield this.cache.get(key)}}*entries(){for(const key of this.accessOrder){yield[key,this.cache.get(key)]}}[Symbol.iterator](){return this.entries()}forEach(callback){for(const[key,value]of this.entries()){callback(value,key,this)}}toArray(){return Array.from(this.entries())}moveToEnd(key){const index=this.accessOrder.indexOf(key);if(index>-1){this.accessOrder.splice(index,1)}this.accessOrder.push(key)}evictLeastRecentlyUsed(){if(this.accessOrder.length>0){const lruKey=this.accessOrder.shift();this.cache.delete(lruKey)}}}exports.LRUCache=LRUCache;