💻 Dev

🛠️ 처음부터 만드는 Chunk — 배열을 지정된 크기로 분할하기

큰 배열을 작은 덩어리로 나눠서 처리해야 할 때가 있습니다. 페이지네이션, 배치 요청, 그리드 레이아웃 구성 같은 상황에서요.

무엇을 하는가?


Chunk는 배열을 지정된 크기의 여러 배열로 나눕니다.
```javascript
const chunk = (arr, size) => {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
};
chunk([1, 2, 3, 4, 5, 6, 7], 3);
// [[1, 2, 3], [4, 5, 6], [7]]
```

어디에 쓰는가?


```javascript
// 페이지네이션
const items = Array.from({length: 25}, (_, i) => i + 1);
const pages = chunk(items, 5); // 5개씩 5페이지
// API 배치 요청 (한 번에 10개씩)
const userIds = [1, 2, 3, ..., 103];
const batches = chunk(userIds, 10);
for (const batch of batches) {
await fetchUsers(batch);
}
// 3열 그리드 렌더링
const products = [...]; // 상품 배열
const rows = chunk(products, 3); // 한 행에 3개
```

재귀로도 만들 수 있습니다


```javascript
const chunk = (arr, size) => {
if (arr.length <= size) return [arr];
return [arr.slice(0, size), ...chunk(arr.slice(size), size)];
};
```

한 걸음 더 — 타입 안전성


```typescript
function chunk(arr: T[], size: number): T[][] {
if (size < 1) throw new Error('Size must be >= 1');
const result: T[][] = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
```
Lodash의 [`_.chunk()`](https://lodash.com/docs/#chunk)도 같은 기능을 제공합니다. 프로덕션에서는 검증된 라이브러리를 추천하지만, 기본 원리는 이 정도입니다.
💬 0
👁 0 views

Comments (0)

💬

No comments yet.

Be the first to comment!