SevdanurGenc's picture
Upload 60 files
63f6453 verified
Raw History Blame Contribute Delete
1.02 kB
/** Kapasite sınırlı, en uzun süre kullanılmayanı (LRU) atan önbellek. */
export class LRUCache {
constructor(capacity) {
if (!Number.isInteger(capacity) || capacity <= 0) {
throw new RangeError('capacity pozitif tam sayı olmalı');
}
this.capacity = capacity;
this.map = new Map();
this.hits = 0;
this.misses = 0;
}
get(key) {
if (!this.map.has(key)) {
this.misses++;
return undefined;
}
const value = this.map.get(key);
this.map.delete(key);
this.map.set(key, value);
this.hits++;
return value;
}
set(key, value) {
if (this.map.has(key)) this.map.delete(key);
this.map.set(key, value);
if (this.map.size > this.capacity) {
const oldest = this.map.keys().next().value;
this.map.delete(oldest);
return oldest;
}
return undefined;
}
get size() {
return this.map.size;
}
hitRate() {
const total = this.hits + this.misses;
return total === 0 ? 0 : this.hits / total;
}
}