(params: {
obj: PlainObject
maxSize: number
})
| 67 | } |
| 68 | |
| 69 | function splitObject(params: { |
| 70 | obj: PlainObject |
| 71 | maxSize: number |
| 72 | }): Chunk<PlainObject>[] { |
| 73 | const { obj, maxSize } = params |
| 74 | const chunks: Chunk<PlainObject>[] = [] |
| 75 | |
| 76 | let currentChunk: Chunk<PlainObject> = { |
| 77 | data: {}, |
| 78 | length: 2, |
| 79 | } |
| 80 | for (const [key, value] of Object.entries(obj)) { |
| 81 | const entryObject = { [key]: value } |
| 82 | const standaloneEntry: Chunk<PlainObject> = { |
| 83 | data: entryObject, |
| 84 | length: getJsonSize(entryObject), |
| 85 | } |
| 86 | |
| 87 | if (standaloneEntry.length > maxSize) { |
| 88 | const overhead = getJsonSize({ [key]: '' }) - 2 |
| 89 | |
| 90 | const items = splitDataWithLengths({ |
| 91 | data: value, |
| 92 | maxChunkSize: maxSize - (getJsonSize({ [key]: '' }) - 2), |
| 93 | }) |
| 94 | |
| 95 | for (const [index, item] of items.entries()) { |
| 96 | const itemWithKey: Chunk<any> = { |
| 97 | data: { [key]: item.data }, |
| 98 | length: item.length + overhead, |
| 99 | } |
| 100 | |
| 101 | if (index < items.length - 1) { |
| 102 | if (key in currentChunk.data) { |
| 103 | chunks.push(currentChunk) |
| 104 | currentChunk = itemWithKey |
| 105 | continue |
| 106 | } |
| 107 | |
| 108 | const candidateChunkLength = |
| 109 | currentChunk.length + |
| 110 | itemWithKey.length - |
| 111 | (currentChunk.length === 2 ? 2 : 3) |
| 112 | if (candidateChunkLength <= maxSize) { |
| 113 | currentChunk.data[key] = item.data |
| 114 | currentChunk.length = candidateChunkLength |
| 115 | continue |
| 116 | } |
| 117 | |
| 118 | if (currentChunk.length > 2) { |
| 119 | chunks.push(currentChunk) |
| 120 | } |
| 121 | currentChunk = itemWithKey |
| 122 | continue |
| 123 | } |
| 124 | |
| 125 | if (currentChunk.length > 2) { |
| 126 | chunks.push(currentChunk) |
no test coverage detected