Skip to content Skip to sidebar Skip to footer

Using .splice Method In Subclass Of Array In Javascript?

I am trying to create a subclass of javascript's Array. I want to initiate subclass with array-type argument and add a method to remove an element from the array (subclass). My cod

Solution 1:

I want to prevent splice method from initiating a new instance of CustomArray class and instead return normal array (an instance of Array object).

Then you need to create a different method with a different name. The semantics of splice are clearly and precisely defined; they form a contract for the Array type. Having your CustomArray violate that contract would mean it isn't an Array anymore, it's something array-like, and shouldn't extend Array.

Since your method is called remove, that's fine; if you want remove to return Array, not CustomArray, you just need to implement the logic yourself:

remove(element) {
  let index = this.indexOf(element);
  if (index > -1) {
    const newLength = this.length - 1;
    while (index < newLength) {
        this[index] = this[index + 1];
        ++index;
    }
    this.length = newLength;
    return [element];
  } 
  return [];
}

Alternately, of course, make CustomArray's constructor work correctly when called by the various Array.prototype methods. (The one you have in the question works just fine, other than logging something you don't expect with console.log.)

Solution 2:

It is possible have splice return a standard array -- so without it calling your constructor. It is by changing the @@species property of your custom class, which determines which constructor will be used. But be aware that this will not only affect splice, but also all other methods that would create a new instance, including map, filter, slice, ...

You can change the @@species property by overwriting the corresponding static getter:

classCustomArrayextendsArray {
  static get [Symbol.species]() { returnArray; } // <-----------constructor(array) {
    console.log('Initiating array:', array)
    super(...array);
  }

  remove(element) {
    let index = this.indexOf(element);
    if (index > -1) {
      returnthis.splice(index, 1); // Now calls Array constructor, not CustomArray
    } 
    return [];
  }

}

var a = ['a', 'b', 'c', 'd', 'e'];

var list = newCustomArray(a)
console.log('list:', list);
console.log('remove:', list.remove('c'));
console.log('list:', list);

// Some examples of effects on other methodsconsole.log(list.map(x => x) instanceofCustomArray); // falseconsole.log(list.filter(x =>1) instanceofCustomArray); // falseconsole.log(list.slice() instanceofCustomArray); // falseconsole.log(list.concat() instanceofCustomArray); // false// Other methods, that do not return a new instance, are not affected:console.log(list.reverse() instanceofCustomArray); // trueconsole.log(list.sort() instanceofCustomArray); // true

Post a Comment for "Using .splice Method In Subclass Of Array In Javascript?"