I am currently delving into TypeScript and seeking guidance on implementing generic collection types. I have discussed dictionaries and HashSets in a previous question; here, I would appreciate any feedback specifically regarding my list type.
The ForEach-Operation seems a bit unconventional to me. I came across it in another question and tried to enhance it by returning true or false to indicate if the iteration was prematurely halted 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 defined in another file:
export interface IForEachFunction<T> {
(callback: T): boolean | void;
}
To utilize my list and the ForEach method, follow this example:
let myList: List<a_type> = new List<a_type>();
let completed: boolean = myList.ForEach(xyz => {
// perform actions with xyz
return false; // interrupts the iteration
return true; // continues to the next element
});
if (completed) // assesses what occurred "during" the iteration
In my opinion, this implementation is satisfactory, but I welcome any constructive criticism. I'm unsure about my usage of ===. Additionally, I'm curious about how to define a function that aligns with the IForEachFunction interface. Can I create a method adhering to the interface definition without employing an anonymous function as depicted above?
Thank you! Ralf