Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 879
civiltomain Avatar asked Aug 26 '15 16:08

civiltomain


2 Answers

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/

like image 157
cdbitesky Avatar answered Sep 28 '22 01:09

cdbitesky


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

No, because TypedArrays cannot change their size. There's no push/pop/shift/unshift methods either.

If you want to delete elements from your array, you typically set them to null, and care for those nulls when traversing the array. This also avoids having to shift around all elements after the ones being deleted.

If you really need this, your best bet is to create a new array and copy elements over it (the ones before the deleted section, the new ones, and then the ones after the deleted section). @cdbitesky has given a nice implementation for this.

like image 21
Bergi Avatar answered Sep 28 '22 02:09

Bergi