logo hsb.horse
← Back to snippets index

Snippets

Uint32Array Helper Functions

A concise TypeScript wrapper for `new Uint32Array` calls. Supports all constructor overloads with type-safe overload definitions.

Published: Updated:

When working with binary data in WebCrypto API and similar contexts, you end up calling new Uint32Array quite often. Writing that lengthy syntax every time gets tedious, so I made a shorter wrapper.

Code

function initUint32(length: number): Uint32Array;
function initUint32(array: ArrayLike<number> | ArrayBufferLike): Uint32Array;
function initUint32(
buffer: ArrayBufferLike,
byteOffset?: number,
length?: number,
): Uint32Array;
function initUint32(
arg1: number | ArrayLike<number> | ArrayBufferLike,
arg2?: number,
arg3?: number,
): Uint32Array {
return typeof arg1 === "number"
? new Uint32Array(arg1)
: "byteLength" in arg1
? new Uint32Array(arg1, arg2, arg3)
: new Uint32Array(arg1);
}

Usage Examples

Initialize with specified length

const arr = initUint32(8);
// Uint32Array(8) [0, 0, 0, 0, 0, 0, 0, 0]

Convert from array

const arr = initUint32([1, 2, 3, 4]);
// Uint32Array(4) [1, 2, 3, 4]

View a portion of ArrayBuffer

const buffer = new ArrayBuffer(32);
const arr = initUint32(buffer, 8, 4);
// Uint32Array(4) [0, 0, 0, 0] - 4 elements from byte 8

Implementation Notes

Using TypeScript function overloads, this provides type-safe access to all three Uint32Array constructor patterns.

  • Pass a number to create an array of that length
  • Pass an array-like object to convert it
  • Pass ArrayBuffer with offset to create a partial view

Internal type guards determine the argument type and dispatch to the appropriate constructor call.