I wrote a tiny LRU cache in JS using Map insertion order. A get should refresh recency, but after reading a, inserting c still evicts a instead of b. What am I misunderstanding about Map order here?
class LRU {
constructor(limit) { this.limit = limit; this.m = new Map(); }
get(k) {
if (!this.m.has(k)) return -1;
const v = this.m.get(k);
this.m.set(k, v);
return v;
}
put(k, v) {
this.m.set(k, v);
if (this.m.size > this.limit) this.m.delete(this.m.keys().next().value);
}
}
Map#set on an existing key updates the value but does not move that key to the end, so for LRU you need delete(k) before set(k, v) in get, and usually in put too when overwriting an existing key.
Yes-specifically because JavaScript Map preserves insertion order, even though a plain object/hash table conceptually does not. The tradeoff is it’s a lightweight LRU for small in-memory cases, but if you need stricter performance guarantees or custom eviction behavior, a doubly linked list plus map is more robust.
Yes-use a Map for O(1) key lookup and a doubly linked list to track recency, so get and put just move a node to the tail and eviction always removes the head.