💻 Dev

🛠️ 처음부터 만드는 LRU Cache — lru-cache 스타일 자동 퇴거 캐시 15줄 구현

왜 LRU Cache?


API 응답, DB 쿼리, 계산 결과... 매번 다시 구하면 낭비입니다.
LRU(Least Recently Used) 는 가장 오래 안 쓴 항목부터 자동으로 버립니다.

핵심 트릭: Map은 순서를 기억한다


JS의 `Map`은 삽입 순서를 유지합니다.
`delete` → `set` 하면 해당 키가 맨 뒤(최신) 로 이동합니다.

15줄 구현


```js
class LRU {
#max; #map = new Map();
constructor(max = 100) { this.#max = max; }
get(key) {
if (!this.#map.has(key)) return undefined;
const v = this.#map.get(key);
this.#map.delete(key);
this.#map.set(key, v); // 맨 뒤로 이동
return v;
}
set(key, val) {
this.#map.delete(key);
this.#map.set(key, val);
if (this.#map.size > this.#max)
this.#map.delete(this.#map.keys().next().value);
return this;
}
has(key) { return this.#map.has(key); }
get size() { return this.#map.size; }
}
```

사용 예시


```js
const cache = new LRU(3);
cache.set('a', 1).set('b', 2).set('c', 3);
cache.get('a'); // 1 — 'a'가 최신으로 이동
cache.set('d', 4); // 용량 초과 → 'b' 자동 퇴거
cache.has('b'); // false
cache.has('a'); // true
```

동작 원리


```
set a,b,c → [a, b, c]
get a → [b, c, a] ← a가 최신으로
set d → [c, a, d] ← b 퇴거!
```

lru-cache 라이브러리와 비교


| 기능 | 우리 구현 | lru-cache v11 |
|------|----------|---------------|
| 기본 LRU | ✅ | ✅ |
| TTL(만료시간) | ❌ | ✅ |
| maxSize(바이트) | ❌ | ✅ |
| fetchMethod | ❌ | ✅ |
15줄로 핵심 LRU를 완성했습니다.
`Map`의 삽입 순서 보장이 이 모든 걸 가능하게 합니다 🗺️
💬 0
👁 0 views

Comments (0)

💬

No comments yet.

Be the first to comment!