-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Janson Bunce
committed
Nov 14, 2024
1 parent
afad920
commit 54992a6
Showing
3 changed files
with
53 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
export const chunkBySize = <T>( | ||
array: T[], | ||
maxSize: number | ||
): { chunks: T[][]; chunkBounds: { start: number; end: number }[] } => { | ||
const chunks: T[][] = []; | ||
const chunkBounds: { start: number; end: number }[] = []; | ||
let currentChunk: T[] = []; | ||
let currentSize = 0; | ||
let startIndex = 0; | ||
|
||
const calculateSize = (item: T): number => { | ||
return Buffer.byteLength(JSON.stringify(item), 'utf8'); | ||
}; | ||
|
||
for (let i = 0; i < array.length; i++) { | ||
const item = array[i]; | ||
const itemSize = calculateSize(item); | ||
|
||
if (currentSize + itemSize > maxSize) { | ||
if (currentChunk.length === 0 && itemSize > maxSize) { | ||
throw new Error( | ||
`Item size (${itemSize} bytes) exceeds the maximum chunk size (${maxSize} bytes).` | ||
); | ||
} | ||
chunks.push(currentChunk); | ||
chunkBounds.push({ start: startIndex, end: i - 1 }); | ||
currentChunk = []; | ||
currentSize = 0; | ||
startIndex = i; | ||
} | ||
|
||
currentChunk.push(item); | ||
currentSize += itemSize; | ||
} | ||
|
||
if (currentChunk.length > 0) { | ||
chunks.push(currentChunk); | ||
chunkBounds.push({ start: startIndex, end: array.length - 1 }); | ||
} | ||
|
||
return { chunks, chunkBounds }; | ||
}; |