Skip to content

Instantly share code, notes, and snippets.

@pboyer
Created February 12, 2017 18:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pboyer/d9241b67b98c359a0012d8ffe6bdd10b to your computer and use it in GitHub Desktop.
Save pboyer/d9241b67b98c359a0012d8ffe6bdd10b to your computer and use it in GitHub Desktop.
A generic, dynamically sized TypedArray in TypeScript
interface TypedArray {
readonly length : number;
readonly [n: number]: number;
BYTES_PER_ELEMENT : number;
set(n : ArrayLike<number>, offset : number) : void;
}
interface TypedArrayConstructor<T extends TypedArray> {
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): T;
}
export class DynamicArray<T extends TypedArray, C extends TypedArrayConstructor<T>> {
private buf : ArrayBuffer;
arr : T;
arrConstructor : C;
constructor(arrayConstructor : C){
this.arrConstructor = arrayConstructor;
this.buf = new ArrayBuffer(8);
this.arr = new this.arrConstructor(this.buf, 0, 0);
}
push(a : T) {
let nreq = (this.arr.length + a.length) * this.arr.BYTES_PER_ELEMENT;
let requiresExpand = nreq >= this.buf.byteLength;
if (requiresExpand) {
// find the new required array length
let nlen = this.buf.byteLength * 2;
while (nlen < nreq){
nlen *= 2;
}
// allocate new buffer
let nbuf = new ArrayBuffer(nlen);
// copy the original array into the new buffer
let narr = new this.arrConstructor(nbuf, 0, this.arr.length);
narr.set(this.arr, 0);
// set the new buf
this.buf = nbuf;
this.arr = narr;
}
let l0 = this.arr.length;
this.arr = new this.arrConstructor(this.buf, 0, l0 + a.length);
this.arr.set(a, l0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment