🛠️ 처음부터 만드는 Chunk — 배열을 일정 크기로 나누기
# Chunk 함수 직접 만들기
배열을 작은 덩어리(chunk)로 나누는 `chunk` 함수를 구현해봅시다. 페이지네이션, 배치 처리, CSV 내보내기 등에서 자주 쓰입니다.
```javascript
const arr = [1, 2, 3, 4, 5, 6, 7];
chunk(arr, 3); // [[1, 2, 3], [4, 5, 6], [7]]
```
```javascript
function chunk(array, size) {
const result = [];
for (let i = 0; i < array.length; i += size) {
result.push(array.slice(i, i + size));
}
return result;
}
```
원리: `size`씩 증가하면서 `slice()`로 부분 배열을 추출하고 결과에 추가합니다.
```javascript
function chunk(array, size) {
if (array.length === 0) return [];
return [array.slice(0, size), ...chunk(array.slice(size), size)];
}
```
```javascript
// 배치 처리: API 한 번에 10개씩
const ids = Array.from({length: 25}, (_, i) => i + 1);
chunk(ids, 10).forEach(batch => {
console.log('배치 전송:', batch);
});
// 페이지네이션: 한 페이지에 5개
const items = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
const pages = chunk(items, 5);
console.log('페이지 2:', pages[1]); // ['F', 'G']
```
```typescript
function chunk(array: T[], size: number): T[][] {
return Array.from(
{length: Math.ceil(array.length / size)},
(_, i) => array.slice(i * size, (i + 1) * size)
);
}
```
팁: `Math.ceil`로 정확한 청크 개수를 계산하면 더 깔끔합니다.
배열을 작은 덩어리(chunk)로 나누는 `chunk` 함수를 구현해봅시다. 페이지네이션, 배치 처리, CSV 내보내기 등에서 자주 쓰입니다.
개념
```javascript
const arr = [1, 2, 3, 4, 5, 6, 7];
chunk(arr, 3); // [[1, 2, 3], [4, 5, 6], [7]]
```
구현 1: 기본
```javascript
function chunk(array, size) {
const result = [];
for (let i = 0; i < array.length; i += size) {
result.push(array.slice(i, i + size));
}
return result;
}
```
원리: `size`씩 증가하면서 `slice()`로 부분 배열을 추출하고 결과에 추가합니다.
구현 2: 재귀 버전
```javascript
function chunk(array, size) {
if (array.length === 0) return [];
return [array.slice(0, size), ...chunk(array.slice(size), size)];
}
```
실전 예제
```javascript
// 배치 처리: API 한 번에 10개씩
const ids = Array.from({length: 25}, (_, i) => i + 1);
chunk(ids, 10).forEach(batch => {
console.log('배치 전송:', batch);
});
// 페이지네이션: 한 페이지에 5개
const items = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
const pages = chunk(items, 5);
console.log('페이지 2:', pages[1]); // ['F', 'G']
```
타입스크립트
```typescript
function chunk
return Array.from(
{length: Math.ceil(array.length / size)},
(_, i) => array.slice(i * size, (i + 1) * size)
);
}
```
팁: `Math.ceil`로 정확한 청크 개수를 계산하면 더 깔끔합니다.
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!