Public
Edited
Jun 1, 2023
Insert cell
Insert cell
m = new Map()
Insert cell
c = new LRUCache(2)
Insert cell
{
c.put("first", 1);
c.put("second", 2);
c.put("third", 3);
return c.get("second");
}
Insert cell
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);
}
}
}

Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more