Typed Arrays in Gecko 2: Float32Array concatenation and expansion

janesconference picture janesconference · Dec 29, 2010 · Viewed 7.2k times · Source

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:

  • as I said before, there is no concatenation method
  • if I try to write past the array length, the array is not expanded (aka this won't work - please note that event.frameBuffer and buffer are both Float32Array and that I don't know what the final length of my buffer will be):

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?

Answer

Fr&#233;d&#233;ric Hamidi picture Frédéric Hamidi · Dec 29, 2010

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);