Напиши LRU кэш через class в JavaScript с применением Typescript и коротко, но понятно…
- User
Напиши LRU кэш через class в JavaScript с применением Typescript и коротко, но понятно объясни принцип работы
Assistant
class LRUCache<K, V> { private capacity: number; private cache: Map<K, V>; constructor(capacity: number) { this.capacity = capacity; this.cache = new Map(); } get(key: K): V | undefined { if (!this.cache.has(key)) { return undefined; } // Перемещаем элемент в конец (делаем "самым свежим") const value = this.cache.get(key)!; this.cache.delete(key); this.cache.set(key, value); return value; } put(key: K, value: V): void { // Если ключ уже существует, удаляем его if (this.cache.has(key)) { this.cache.delete(key); } // Если достигнут лимит, удаляем самый старый элемент if (this.cache.size >= this.capacity) { const firstKey = this.cache.keys().next().value; this.cache.delete(firstKey); } // Добавляем новый элемент в конец this.cache.set(key, value); } size(): number { return this.cache.size; } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.