UNPKG

@sap/xssec

Version:

XS Advanced Container Security API for node.js

52 lines (45 loc) 1.61 kB
/** * Implements a Least Recently Used (LRU) cache using a Map. * Due to the nature of Map, the order of insertion is preserved in keys() which allows for an implementation with average O(1) complexity for get and put. * @param {number} capacity */ class LRUCache { /** * Creates an instance of LRUCache. * @param {number} size - The maximum number of items the cache can hold. */ constructor(size) { this.size = size; this.map = new Map(); } /** * Retrieve a value from the cache. * @param {string} key - The key of the item to retrieve. * @returns {*} The value associated with the key, or null if the key does not exist. */ get(key) { if (!this.map.has(key)) return null; const value = this.map.get(key); // accessed key must be re-inserted at end of queue for LRU strategy this.map.delete(key); this.map.set(key, value); return value; } /** * Insert or update a value in the cache. * @param {string} key - The key of the item to insert or update. * @param {*} value - The value to associate with the key. */ set(key, value) { if (this.map.has(key)) { // existing key must be re-inserted at end of queue for LRU strategy this.map.delete(key); } else if (this.map.size >= this.size) { // Map.keys() is in insertion order const oldestKey = this.map.keys().next().value; this.map.delete(oldestKey); } this.map.set(key, value); } } module.exports = LRUCache;