WebCrypto API 등에서 바이너리 데이터를 다루면 new Uint8Array를 자주 호출하게 됩니다. 매번 긴 구문을 쓰는 건 귀찮아서 간결하게 쓸 수 있는 래퍼를 만들었습니다.
코드
const BYTE_LENGTH = "byteLength";
export function toU8Array(length: number): Uint8Array;export function toU8Array( array: ArrayLike<number> | ArrayBufferLike): Uint8Array;export function toU8Array( buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array;export function toU8Array( arg1: number | ArrayLike<number> | ArrayBufferLike, arg2?: number, arg3?: number): Uint8Array { return typeof arg1 === "number" ? new Uint8Array(arg1) : BYTE_LENGTH in arg1 ? new Uint8Array(arg1, arg2, arg3) : new Uint8Array(arg1);}사용 예
지정한 길이로 초기화
const arr = toU8Array(32);// Uint8Array(32) [0, 0, 0, ...] - 랜덤값용 버퍼로Base64 디코딩 후 변환
const base64 = "SGVsbG8gV29ybGQh";const binary = Uint8Array.from(atob(base64), c => c.charCodeAt(0));const arr = toU8Array(binary);ArrayBuffer 일부를 뷰로 가져오기
const buffer = new ArrayBuffer(64);const arr = toU8Array(buffer, 16, 16);// 16바이트부터 16요소분의 뷰구현 포인트
BYTE_LENGTH를 상수로 정의해 minify 시 최적화를 고려했습니다. 타입 가드 순서도 중요한데, 먼저 number인지 체크하고, 다음에 byteLength 프로퍼티 유무로 ArrayBufferLike를 판정하며, 그 외는 ArrayLike로 처리합니다.
간단한 변환이라면 new Uint8Array만으로 충분하지만, 타입 안전하게 통일된 인터페이스로 다루고 싶을 때 이 래퍼가 유효합니다.
hsb.horse