🛠️ 처음부터 만드는 Chunk — 배열을 지정 크기로 나누기
언제 필요한가?
대량의 데이터를 일정 크기의 배치로 나눠서 처리할 때 자주 쓰입니다. API 한 번에 10개씩 요청하기, 파일을 1MB 청크로 업로드하기, 표에 페이지네이션 구현하기 등이 예입니다.
기본 구현
```typescript
function chunk
if (size <= 0) throw new Error('Size must be positive');
const result: T[][] = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
// 사용
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const chunked = chunk(items, 3);
// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```
실제 사용 예제
```typescript
// 배치 API 요청
const userIds = Array.from({ length: 100 }, (_, i) => i + 1);
const batches = chunk(userIds, 10);
for (const batch of batches) {
const users = await api.fetchUsers(batch); // 10개씩 요청
processUsers(users);
}
// 대용량 파일 업로드
const fileChunks = chunk(buffer, 1024 * 1024); // 1MB씩
for (let i = 0; i < fileChunks.length; i++) {
await uploadChunk(fileChunks[i], i);
}
```
심화: Generator 버전 (메모리 효율)
```typescript
function* chunkGenerator
for (let i = 0; i < arr.length; i += size) {
yield arr.slice(i, i + size);
}
}
// 대용량 배열도 메모리 안전
for (const batch of chunkGenerator(hugeArray, 1000)) {
process(batch); // 1000개씩만 메모리에 로드
}
```
참고
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!