0

I created a class, that extends Array:

export class Collection<T> extends Array<T> {
    constructor(items?: Array<T>) {
        super(...items);

        Object.setPrototypeOf(this, Object.create(Collection.prototype));
    }

    whereKey(key: string, value: any): T {
        for(let i = 0; i < this.length; i++) {
            if(this[i][key] === value) {
                return this[i];
            }
        }
    }

    removeAt(index: number) {
        this.splice(index, 1);
    }
}

However, using anything standard array method, like splice(), or even filter(), doesn't work. I get ImportsHomeComponent.html:15 ERROR TypeError: CreateListFromArrayLike called on non-object as an error. Literally the only method I can use is push.

I have created the collection like so:

getImportTests(): Observable<Collection<ImportTest>> {
    return this.http.get<Collection<IImportTest>>(route('imports/import-tests')).map((importTests: Collection<IImportTest>) => {
        return new Collection<ImportTest>(importTests.map((importTest: IImportTest) => {
            return new ImportTest(importTest);
        }));
    });
}

And then tried to remove an element like so:

this.importTests.removeAt(this.importTests.indexOf(importTest));

I only really need to use a collection but of the whereKey method, but I'm open to anything as this is driving me crazy.

1
  • I don't understand what exactly you want to achieve with this collection. Wouldn't array's find work as well? Commented Feb 20, 2018 at 19:34

1 Answer 1

1

The Collection constructor does not call the super Array constructor properly. Notice the structure is different:

new Collection(["a", "b"]) =>
    Array(2)0: "a"1: "b"length: 2__proto__: Collection

new Array(["a", "b"]) =>
    Array(1)0: (2) ["a", "b"]length: 1__proto__: Array(0)

Try this:

constructor(...items) {
        super(...items);

        Object.setPrototypeOf(this, Object.create(Collection.prototype));
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.