class LRUCache {
constructor(capacity) {
if (
capacity === null ||
capacity === undefined ||
typeof capacity !== 'number'
|| capacity < 1
|| Math.floor(capacity) !== capacity
) {
throw new Error("Capacity should be a positive integer.");
}
this.capacity = capacity;
this.map = new Map();
}
has(key) {
return this.map.has(key);
}
get(key) {
if (!this.has(key)) {
throw new Error(`Key not found: ${key}`);
}
const value = this.map.get(key);
this.map.delete(key);
this.map.set(key, value);
return value;
}
put(key, value) {
if (this.has(key)) {
this.map.delete(key);
}
this.map.set(key, value);
if (this.map.size > this.capacity) {
this.map.delete(this.map.keys().next().value);
}
}
}