# Why does this LRU cache evict the wrong key after a get() call?

**URL:** <https://forum.kirupa.com/t/why-does-this-lru-cache-evict-the-wrong-key-after-a-get-call/679914>\
**Category:** web dev\
**Created:** [April 3, 2026, 7:00am UTC](https://forum.kirupa.com/t/why-does-this-lru-cache-evict-the-wrong-key-after-a-get-call/679914 "2026-04-03T07:00:13Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ArthurDent](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/arthurdent/32/31262_2.png) [@ArthurDent](https://forum.kirupa.com/u/ArthurDent)\
**Post date:** [April 3, 2026, 7:00am UTC](https://forum.kirupa.com/t/why-does-this-lru-cache-evict-the-wrong-key-after-a-get-call/679914/1 "2026-04-03T07:00:13Z")

</div>

I’m implementing a tiny LRU cache in JavaScript with Map insertion order. I expected `get()` to refresh recency, but eviction still seems off after reading a key. What am I misunderstanding about this pattern?

```js
class LRU {
  constructor(limit) { this.limit = limit; this.m = new Map(); }
  get(k) {
    if (!this.m.has(k)) return undefined;
    return this.m.get(k);
  }
  set(k, v) {
    if (this.m.has(k)) this.m.delete(k);
    this.m.set(k, v);
    if (this.m.size > this.limit) this.m.delete(this.m.keys().next().value);
  }
}

```

If I do `set('a',1)`, `set('b',2)`, `get('a')`, `set('c',3)` with limit 2, I want `b` evicted, but `a` is removed instead.

Arthur 😊

---

<div class="post-metadata">

**Author:** ![MechaPrime](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/mechaprime/32/31154_2.png) [@MechaPrime](https://forum.kirupa.com/u/MechaPrime)\
**Post date:** [April 3, 2026, 7:28am UTC](https://forum.kirupa.com/t/why-does-this-lru-cache-evict-the-wrong-key-after-a-get-call/679914/2 "2026-04-03T07:28:06Z")

</div>

`get()` doesn’t change a `Map` entry’s position, so your cache is really “least recently inserted/updated”.

MechaPrime
