🛠️ 처음부터 만드는 LRU Cache — Map의 삽입 순서를 활용한 O(1) 캐시 20줄 구현
왜 LRU Cache인가?
API 응답 캐싱, 이미지 메모리 관리, DB 쿼리 재사용 — "가장 오래 안 쓴 걸 버려라"는 전략이 어디서든 필요합니다. Redis의 `maxmemory-policy`, React Query의 `gcTime`, 브라우저 HTTP 캐시 모두 LRU 기반입니다.
핵심 트릭
JS의 `Map`은 삽입 순서를 보장합니다. LinkedList 없이 O(1) LRU가 가능한 이유:
```typescript
class LRUCache
private cache = new Map
constructor(private capacity: number) {}
get(key: K): V | undefined {
if (!this.cache.has(key)) return undefined;
const value = this.cache.get(key)!;
this.cache.delete(key);
this.cache.set(key, value);
return value;
}
set(key: K, value: V): void {
if (this.cache.has(key)) this.cache.delete(key);
else if (this.cache.size >= this.capacity) {
this.cache.delete(this.cache.keys().next().value!);
}
this.cache.set(key, value);
}
}
```
동작 확인
```typescript
const cache = new LRUCache
cache.set("a", 1);
cache.set("b", 2);
cache.set("c", 3);
cache.get("a"); // 1 — "a"가 최근으로 이동
cache.set("d", 4); // 용량 초과 → "b" 퇴거 (가장 오래 안 쓴 것)
cache.get("b"); // undefined
```
확장 아이디어
면접 단골 질문이기도 하죠. "LinkedList + HashMap"이 교과서 답이지만, JS에선 Map 하나로 끝납니다. `lru-cache` npm 패키지(주간 다운로드 2억+)의 핵심이 바로 이 패턴입니다.
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!