Implementazione di cache LRU in JavaScript

Livello 5546 battiture

La cache LRU elimina l'elemento meno recentemente usato quando la capacità viene superata.

Codice JavaScript

// Cache LRU (Least Recently Used) usando Map
1class LRUCache {
2 constructor(capacity) {
// Impostare il numero massimo di elementi
3 this.capacity = capacity;
// Map mantiene l'ordine di inserimento
4 this.cache = new Map();
5 }
6 get(key) {
// Restituire -1 se la chiave non esiste
7 if (!this.cache.has(key)) return -1;
// Ottenere il valore
8 const val = this.cache.get(key);
// Spostare alla fine (usato più recentemente) reinserendo
9 this.cache.delete(key);
10 this.cache.set(key, val);
11 return val;
12 }
13 put(key, value) {
// Eliminare se esiste (per aggiornare la posizione)
14 this.cache.delete(key);
// Aggiungere alla fine (usato più recentemente)
15 this.cache.set(key, value);
// Se oltre la capacità, rimuovere il più vecchio (primo)
16 if (this.cache.size > this.capacity) {
// keys().next().value è la prima chiave (la più vecchia)
17 this.cache.delete(this.cache.keys().next().value);
18 }
19 }
20}
21
// Creare cache con capacità 2
22const cache = new LRUCache(2);
// Aggiungere elementi
23cache.put(1, "a"); cache.put(2, "b");
// Ottenere 1 (lo rende usato più recentemente)
24console.log(cache.get(1));
// Aggiungere 3, elimina 2 (usato meno recentemente)
25cache.put(3, "c");
// 2 è stato eliminato, restituisce -1
26console.log(cache.get(2));

Output

a
-1
Esercitati a digitare questo codice

Esercitati a digitare questo codice. I risultati non vengono registrati in classifica.

Simboli in questo codice

I simboli che digiti in questo codice JavaScript e quante volte compaiono.

  • .× 30
  • (× 23
  • )× 23
  • ;× 16
  • ,× 6
  • "× 6
  • {× 5
  • }× 5
  • =× 4
  • -× 1

Altri esempi JavaScript di livello 5

← Pratica di digitazione JavaScript