🛠️ 처음부터 만드는 Deep Clone — 깊게 복사하기
객체나 배열을 복사할 때 단순 할당은 참조만 복사합니다. React 상태 관리나 API 응답 처리에서 깊은 구조를 안전하게 복사해야 할 때가 많습니다.
```javascript
const original = { user: { name: 'John', age: 30 } };
const shallow = { ...original };
shallow.user.name = 'Jane';
console.log(original.user.name); // 'Jane' — 원본이 변함!
```
```javascript
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
if (Array.isArray(obj)) return obj.map(item => deepClone(item));
const cloned = {};
for (const key in obj) {
cloned[key] = deepClone(obj[key]);
}
return cloned;
}
```
```javascript
function deepClone(obj, seen = new WeakMap()) {
if (obj === null || typeof obj !== 'object') return obj;
if (seen.has(obj)) return seen.get(obj);
if (obj instanceof Date) return new Date(obj);
const cloned = Array.isArray(obj) ? [] : {};
seen.set(obj, cloned);
for (const key in obj) {
cloned[key] = deepClone(obj[key], seen);
}
return cloned;
}
```
React 상태 업데이트 (불변성 유지)
Redux/Zustand 스토어
API 응답 안전한 변환
폼 초기값 보존
참고: structuredClone() (최신 브라우저) 또는 성능이 중요하면 구조적 공유(structural sharing)를 검토하세요.
얕은 복사 vs 깊은 복사
```javascript
const original = { user: { name: 'John', age: 30 } };
const shallow = { ...original };
shallow.user.name = 'Jane';
console.log(original.user.name); // 'Jane' — 원본이 변함!
```
기본 구현
```javascript
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
if (Array.isArray(obj)) return obj.map(item => deepClone(item));
const cloned = {};
for (const key in obj) {
cloned[key] = deepClone(obj[key]);
}
return cloned;
}
```
심화: Date와 순환 참조
```javascript
function deepClone(obj, seen = new WeakMap()) {
if (obj === null || typeof obj !== 'object') return obj;
if (seen.has(obj)) return seen.get(obj);
if (obj instanceof Date) return new Date(obj);
const cloned = Array.isArray(obj) ? [] : {};
seen.set(obj, cloned);
for (const key in obj) {
cloned[key] = deepClone(obj[key], seen);
}
return cloned;
}
```
언제 사용하나?
참고: structuredClone() (최신 브라우저) 또는 성능이 중요하면 구조적 공유(structural sharing)를 검토하세요.
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!