Search code examples
javascriptecmascript-6typed-arrays

Does splice exist for TypedArrays or is there an equivalent?


Is there or is there ever going to be an equivalent of Array.prototype.splice for TypedArrays?

I want to be able to delete a range of items from a TypedArray.


Solution

  • So TypedArrays in ES6 are not classical Javascript arrays, but closer to an API for a underlying binary buffer (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays).

    Since splice mutates the actual length of array it isn't usable with TypedArrays (http://www.es6fiddle.net/idt0ugqo/).

    You can create similar behavior by creating your own splice (although it will be slower).

    This is a simple equivalent except that it doesn't account for all nuances of `splice. As @bergi commented, I don't allow negative values.

    function splice(arr, starting, deleteCount, elements) {
      if (arguments.length === 1) {
        return arr;
      }
      starting = Math.max(starting, 0);
      deleteCount = Math.max(deleteCount, 0);
      elements = elements || [];
    
    
      const newSize = arr.length - deleteCount + elements.length;
      const splicedArray = new arr.constructor(newSize);
    
      splicedArray.set(arr.subarray(0, starting));
      splicedArray.set(elements, starting);
      splicedArray.set(arr.subarray(starting + deleteCount), starting + elements.length);
      return splicedArray;
    };
    
    splice(new Uint8Array([1,2,3]), 0, 1); // returns Uint8Array([1,3])
    

    http://www.es6fiddle.net/idt3epy2/