TypeScript Generic Collection: List

Viewed 8192

I am trying to learn TypeScript, and need some advice on implementing generic collection types. I put the dictionary and HashSet in another question, here I'd like any advice on my list type.

Especially the ForEach-Operation looks a bit strange. I think I found it in another question here, and "improved" by returning true or false to give feedback if the iteration was stopped early or completed.

import { IForEachFunction } from "./IForEachFunction"

export class List<T> {
    private _items: Array<T>;

    public constructor() {
        this._items = [];
    }

    public get Count(): number {
        return this._items.length;
    }

    public Item(index: number): T {
        return this._items[index];
    }

    public Add(value: T): void {
        this._items.push(value);
    }

    public RemoveAt(index: number): void {
        this._items.splice(index, 1);
    }

    public Remove(value: T): void {
        let index = this._items.indexOf(value);
        this.RemoveAt(index);
    }

    public ForEach(callback: IForEachFunction<T>): boolean {
        for (const element of this._items) {
            if (callback(element) === false) {
                return false;
            }
        }

        return true;
    }
}

The ForEach-Iteration relies on an interface from another file:

export interface IForEachFunction<T> {
    (callback: T): boolean | void;
}

You would use my list and the ForEach-Method like this:

let myList: List<a_type> = new List<a_type>();
let completed: boolean = myList.ForEach(xyz => {
    // do something with xyz
    return false; // aborts the iteration
    return true; // continues with the next element
});
if (completed) // we can see what happened "during" the iteration

I think this is not bad, but I'd appreciate any input. I am not sure if I use the === correctly. Another question which I really like to know: How could I define a function with the interface IForEachFunction? I do not really "re-use" that interface visibly, I always declare an anonymous method as shown above. If I wanted to call a method having the interface definition, is that possible?

Thanks! Ralf

1 Answers
Related