0

I would like to have an array based on Uint32Array. The length of the array should grow incrementally while amount of its elements grows. At the same time I want "length" property return the number of elements, not the size of the underlying array. For instance:

var a = new myArray();
a.length; // returns 0, the size of underlying array is 10
a.add(0);
a.length; // returns 1, the size of underlying array is 10
...
a.add(9);
a.length; // returns 10, the size of underlying array is 10
a.add(10);
a.length; // returns 11, the size of underlying array is 20

The code below shows how I tried to implement it. The only obstacle is the access to "length" property of the original array. The "parent" word in the code is only for the example. If I replace it with "this.prototype" it says "this.prototype.length" in undefined.

Is it possible to work around it?

var myArray = function() {
this._length = 0;
return this;

// defining the getter for "length" property
Object.defineProperty(this, "length", {
    get: function() {
      return this._length;
    },
};

myArray.prototype = new Uint32Array(myArray.increment);
myArray.increment = 10;
myArray.add = function(val) {
   if (this.length <= parent.length) {
      _a = new Uint32Array(parent.length + myArray.increment);
      _a.set(this);
      this = _a;
    };
   this[this.length++] = val;
};
Dmitry
  • 1,556
  • 1
  • 14
  • 26

1 Answers1

1

This is what I would do:

function MyArray(increment) {
    var array = new Uint32Array(increment);
    var length = 0;

    Object.defineProperty(this, "length", {
        get: function () {
            return length;
        }
    });

    this.add = function (value) {
        if (length === array.length) {
            var ext = new Uint32Array(length + increment);
            ext.set(array);
            array = ext;
        }

        var index = length++;
        array[index] = value;

        Object.defineProperty(this, index, {
            get: function () {
                return array[index];
            },
            set: function (value) {
                array[index] = value;
            }
        });
    };
}

Then you create your array as follows:

var a = new MyArray(10);
a.length; // returns 0, the size of underlying array is 10
a.add(0);
a.length; // returns 1, the size of underlying array is 10
...
a.add(9);
a.length; // returns 10, the size of underlying array is 10
a.add(10);
a.length; // returns 11, the size of underlying array is 20

You're doing inheritance in JavaScript wrong. Read about it here.

You can see the demo here: http://jsfiddle.net/dWKTX/1/

Community
  • 1
  • 1
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299