【发布时间】:2018-01-01 01:09:25
【问题描述】:
我正在尝试学习 TypeScript,并且需要一些关于实现泛型集合类型的建议。我将字典和 HashSet 放在另一个问题中,在这里我想对我的列表类型提出任何建议。
尤其是 ForEach-Operation 看起来有点奇怪。我想我在这里的另一个问题中找到了它,并通过返回 true 或 false 来“改进”以在迭代提前停止或完成时提供反馈。
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;
}
}
ForEach-Iteration 依赖于另一个文件的接口:
export interface IForEachFunction<T> {
(callback: T): boolean | void;
}
你会像这样使用我的列表和 ForEach-Method:
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
我认为这还不错,但如果有任何意见,我将不胜感激。我不确定我是否正确使用了 ===。 另一个我很想知道的问题:如何使用接口 IForEachFunction 定义函数?我并没有真正“重用”该接口,我总是声明一个匿名方法,如上所示。如果我想调用具有接口定义的方法,可以吗?
谢谢! 拉尔夫
【问题讨论】:
-
FWIW,
Array#every和你的ForEach方法一样。我会坚持使用普通数组而不是编写包装器。 -
这个问题似乎有点太宽泛了,因为我不知道如何给出一个不能解决所有不同问题的独立答案:你的 ForEach 函数看起来不错。您对
===的使用很好。您可以使用如下接口定义定义函数:var forEachFunc: IForEachFunction<string> = function(s) { return !!s; }。方法和属性通常以小写字母开头。我假设您实现List类是为了充实自己,而不是在“现实世界”中使用,因为正如其他人所说,在大多数情况下最好使用 js 数组。
标签: list typescript collections