🛠️ 처음부터 만드는 Chunk — 배열을 일정 크기로 분할하기
배열을 작은 덩어리(청크)로 나누는 것은 배치 처리, API 레이트 제한, 메모리 관리에서 자주 필요합니다.
```javascript
function chunk(array, size) {
if (size <= 0) throw new Error('size must be > 0');
const result = [];
for (let i = 0; i < array.length; i += size) {
result.push(array.slice(i, i + size));
}
return result;
}
// 사용 예
const nums = [1, 2, 3, 4, 5, 6, 7];
console.log(chunk(nums, 3));
// [[1, 2, 3], [4, 5, 6], [7]]
```
```javascript
async function uploadInBatches(files, batchSize = 10) {
const batches = chunk(files, batchSize);
for (const batch of batches) {
const promises = batch.map(file => uploadFile(file));
const results = await Promise.all(promises);
console.log(`Uploaded ${results.length} files`);
}
}
```
```javascript
function* chunkGenerator(array, size) {
for (let i = 0; i < array.length; i += size) {
yield array.slice(i, i + size);
}
}
// 메모리가 많이 필요한 대용량 배열도 안전하게 처리
for (const batch of chunkGenerator(millionItems, 100)) {
processBatch(batch);
}
```
팁: Lodash의 `_.chunk()`([공식 문서](https://lodash.com/docs/#chunk))와 동일한 동작입니다. 프로덕션에서는 검증된 라이브러리 사용을 권장합니다.
기본 구현
```javascript
function chunk(array, size) {
if (size <= 0) throw new Error('size must be > 0');
const result = [];
for (let i = 0; i < array.length; i += size) {
result.push(array.slice(i, i + size));
}
return result;
}
// 사용 예
const nums = [1, 2, 3, 4, 5, 6, 7];
console.log(chunk(nums, 3));
// [[1, 2, 3], [4, 5, 6], [7]]
```
실무 활용: 배치 API 호출
```javascript
async function uploadInBatches(files, batchSize = 10) {
const batches = chunk(files, batchSize);
for (const batch of batches) {
const promises = batch.map(file => uploadFile(file));
const results = await Promise.all(promises);
console.log(`Uploaded ${results.length} files`);
}
}
```
제너레이터 버전 (메모리 효율)
```javascript
function* chunkGenerator(array, size) {
for (let i = 0; i < array.length; i += size) {
yield array.slice(i, i + size);
}
}
// 메모리가 많이 필요한 대용량 배열도 안전하게 처리
for (const batch of chunkGenerator(millionItems, 100)) {
processBatch(batch);
}
```
팁: Lodash의 `_.chunk()`([공식 문서](https://lodash.com/docs/#chunk))와 동일한 동작입니다. 프로덕션에서는 검증된 라이브러리 사용을 권장합니다.
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!