Search code examples
javascriptarraystyped-arrays

How to read typed array with another arrays type


I am inside a function, array1 and array2 are it's paramentrs which are typed arrays, any of these: Uint32ArrayorInt32ArrayorFloat64ArrayorUint8Array
Inside this function how can I convert array1 raw data into a typed array equal to array2 type
something like this:

function readArray(array1, array2)
{
    var a = new array2Type(array1.buffer);
    //rest of the code where "a" is used
} 

array2Type is not a valid code, what would be the correct way to do the conversion?


Solution

  • You can create a new typed array view based on a source one doing this:

    var dstArray = new window[srcArray.constructor.name](srcArray.buffer);
    

    Implemented in the function:

    function readArray(array1, array2) {
      var a = new window[array2.constructor.name](array1.buffer);
      console.log(a.constructor.name);
    }
    
    var a1 = new Uint32Array(1);
    var a2 = new Float32Array(1);
    readArray(a1, a2); //Should log Float32Array

    You will however need to add some sanitizing as for example a Uint32Array need four bytes as a minimum, and if you pass in a 1-length Uint16Array it will fail since there are only two bytes. And so forth.