바이너리 데이터를 다루다 별면, 여러 Uint8Array를 결합하고 싶은 상황이 생깁니다. 예를 들어 파일을 분할 업로드하여 수신한 청크를 원래대로 복원할 때 등입니다.
코드
function mergeU8Array(...arrays: Uint8Array[]): Uint8Array { const total = arrays.reduce((acc, cur) => acc + cur.byteLength, 0);
let offset = 0; return arrays.reduce<Uint8Array>((acc, cur) => { acc.set(cur, offset); offset += cur.byteLength; return acc; }, new Uint8Array(total));}사용 예시
여러 배열 합치기
const part1 = new Uint8Array([1, 2, 3]);const part2 = new Uint8Array([4, 5, 6]);const part3 = new Uint8Array([7, 8, 9]);
const merged = mergeU8Array(part1, part2, part3);// Uint8Array(9) [1, 2, 3, 4, 5, 6, 7, 8, 9]빈 배엏도 처리 가능
const merged = mergeU8Array(new Uint8Array(), part1);// 빈 배열은 무시되고 결합됩니다구현 설명
- 먼저 reduce로 모든 배열의 총 바이트 길이를 계산
- 해당 크기로 새로운 Uint8Array를 할당
- 각 배열을 set 메서드로 순차적으로 기록
- offset을 진행하며 배치 위치를 관리
reduce 안에서 부작용이 있는 작업을 수행하고 있지만, 바이트 단위 복사가 발생하지 않는 set 메서드를 사용하여 상대적으로 효율적으로 구현했습니다.
hsb.horse