javascriptarraysgeckotyped-arrays

Typed Arrays in Gecko 2: Float32Array concatenation and expansion


I'm a bit confused with Javascript Typed Arrays.

What I have are several Float32Array s, that have no concat method. I don't know how many are them in advance, btw. I'd like to concatenate them all inside another Float32Array, but:


var length_now = buffer.length;
for (var i = 0; i < event.frameBuffer.length; i += 1) {
      buffer [length_now + i] = event.frameBuffer[i];
}

The only solution I found is to copy the Float32Array in a regular array, that's definitely not what I want. How would you do, stackoverflowers?


Solution

  • Typed arrays are based on array buffers, which cannot be resized dynamically, so writing past the end of the array or using push() is not possible.

    One way to achieve what you want would be to allocate a new Float32Array, large enough to contain both arrays, and perform an optimized copy:

    function Float32Concat(first, second)
    {
        var firstLength = first.length,
            result = new Float32Array(firstLength + second.length);
    
        result.set(first);
        result.set(second, firstLength);
    
        return result;
    }
    

    That would allow you to write:

    buffer = Float32Concat(buffer, event.frameBuffer);