Question

I've got an Uint8Array on which I want to use the slice method.

So I took advantage of the array slice method like this:

Array.prototype.slice.call(array, start, end);

Now I want to outsource some common used functions like this.
I tried it with

var utils = {
   slice: function() {
     return Array.prototype.slice.apply(this, arguments);
   }
};

But apparently I misunderstood how it really works. Can anybody explain this to me and how to achieve it to get working?

Was it helpful?

Solution

Your problem lies in that this is not what you think it is. If you call utils.slice(foo, 1, 2), this will be utils.

Depending on how you want to call it, you could pass the object you want to operate on as first argument, then you would do:

var utils = {
   slice: function() {
     // The object we're operating on
     var self = arguments[0];
     // The rest of the arguments
     var args = Array.prototype.slice.call(arguments, 1);

     return Array.prototype.slice.apply(self, args);
   }
};

Usage:

var someSlice = utils.slice(someArray, 2, 14);

Another (perhaps clearer) option is to just use named arguments:

var utils = {
    slice: function(array, from, to) {
        return Array.prototype.slice.call(array, from, to);
    }
};

This will work the same way.

Update: I got curious why Uint8Array doesn't have slice, and I found out about subarray:

Int8Array subarray(
  long begin,
  optional long end
);

Note that

Note: Keep in mind that this is creating a new view on the existing buffer; changes to the new object's contents will impact the original object and vice versa.

It might be the case that this is what you want -- I'm betting on it being a lot more efficient -- if you don't need to copy the data, that is!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top