How can I merge TypedArrays in JavaScript?

后端 未结 7 489
说谎
说谎 2020-12-09 01:01

I\'d like to merge multiple arraybuffers to create a Blob. however, as you know, TypedArray dosen\'t have \"push\" or useful methods...

E.g.:

var a          


        
7条回答
  •  无人及你
    2020-12-09 01:32

    I always use this function:

    function mergeTypedArrays(a, b) {
        // Checks for truthy values on both arrays
        if(!a && !b) throw 'Please specify valid arguments for parameters a and b.';  
    
        // Checks for truthy values or empty arrays on each argument
        // to avoid the unnecessary construction of a new array and
        // the type comparison
        if(!b || b.length === 0) return a;
        if(!a || a.length === 0) return b;
    
        // Make sure that both typed arrays are of the same type
        if(Object.prototype.toString.call(a) !== Object.prototype.toString.call(b))
            throw 'The types of the two arguments passed for parameters a and b do not match.';
    
        var c = new a.constructor(a.length + b.length);
        c.set(a);
        c.set(b, a.length);
    
        return c;
    }
    

    The original function without checking for null or types

    function mergeTypedArraysUnsafe(a, b) {
        var c = new a.constructor(a.length + b.length);
        c.set(a);
        c.set(b, a.length);
    
        return c;
    }
    

提交回复
热议问题