0

what I'm trying to accomplish is , a sub/child class of Array<T> , that has my own custom methods , but am facing a problem here , I can't edit the items within the Array ...

lets see an example to clarify what I'm doing:

export class Collection<T> extends Array<T>
{
    remove(key, value) {
        this = this.filter(function (el) {
            return el[key] !== value;
        });
    }
}

so I can have an Array of User

let users:Collection<User> = [];

//add stuff etc ...

//then I can say 
users.remove('name','Jhone Doe');

so it remove any items that has a key name and value Jhone Doe , but clearly I can't assign the this instance , so how would I tackle that?

Abanoub
  • 3,623
  • 16
  • 66
  • 104
  • or just add Array extension methods https://stackoverflow.com/questions/38434337/how-to-create-an-extension-method-in-typescript-for-date-data-type – Slai Sep 05 '17 at 23:12

1 Answers1

0

First, remove won't be found at all unless you declare your array as

let users: Collection<User> = [];

Second, if you want to remove the elements in place, you need to use splice, or do it yourself:

remove(key, value) {
    let j = 0;

    for (const el of this) if (el[key] !== value) this[j++] = el;

    this.length = j;
}

Even after you've done all this, I wouldn't be surprised if you ran into unexpected behavior, especially as relates to length. Subclassing exotic objects such as arrays is still a work in progress.

  • -about declaring it as `Array` instead of `Collection` it was a mistake , I edited that, there is no way to gain full access over the `Array` properties ? – Abanoub Sep 05 '17 at 20:51
  • What do you mean when you say "gain full access over the `Array` properties"? You do have full access. What you cannot do is swap the object out from under itself. You can't to that with any kind of object. –  Sep 06 '17 at 03:26