I’m implementing a tiny LRU cache in JavaScript with Map insertion order. Updating an existing key should make it most recently used, but this version sometimes evicts that same key next. What am I misunderstanding about Map order here, and what’s the minimal fix?
class LRU {
constructor(limit) { this.limit = limit; this.map = new Map(); }
get(k) { return this.map.get(k); }
put(k, v) {
this.map.set(k, v);
if (this.map.size > this.limit) {
const oldest = this.map.keys().next().value;
this.map.delete(oldest);
}
}
}
MechaPrime