Implementação de cache LRU em JavaScript
Nível 5546 toques
O cache LRU despeja o item menos recentemente usado quando a capacidade é excedida.
Código JavaScript
// Cache LRU (Menos Recentemente Usado) usando Map1class LRUCache {2 constructor(capacity) { // Definir número máximo de itens3 this.capacity = capacity; // Map mantém a ordem de inserção4 this.cache = new Map();5 }6 get(key) { // Retornar -1 se a chave não existir7 if (!this.cache.has(key)) return -1; // Obter o valor8 const val = this.cache.get(key); // Mover para o final (mais recentemente usado) reinserindo9 this.cache.delete(key);10 this.cache.set(key, val);11 return val;12 }13 put(key, value) { // Deletar se existir (para atualizar posição)14 this.cache.delete(key); // Adicionar ao final (mais recentemente usado)15 this.cache.set(key, value); // Se exceder capacidade, remover o mais antigo (primeiro)16 if (this.cache.size > this.capacity) { // keys().next().value é a primeira chave (a mais antiga)17 this.cache.delete(this.cache.keys().next().value);18 }19 }20}21 // Criar cache com capacidade 222const cache = new LRUCache(2);// Adicionar itens23cache.put(1, "a"); cache.put(2, "b");// Obter 1 (torna-o mais recentemente usado)24console.log(cache.get(1));// Adicionar 3, despeja 2 (menos recentemente usado)25cache.put(3, "c");// 2 foi despejado, retorna -126console.log(cache.get(2));Saída
a -1
Pratique digitando este código. Os resultados não são registrados no ranking.
Símbolos deste código
Os símbolos que você digita neste código JavaScript e quantas vezes aparecem.
.× 30(× 23)× 23;× 16,× 6"× 6{× 5}× 5=× 4-× 1