List.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. /**
  2. * List容器
  3. */
  4. export class List<T> {
  5. private _items: T[];
  6. constructor(array?: T[]) {
  7. if (array)
  8. this._items = array;
  9. else
  10. this._items = [];
  11. }
  12. /**
  13. * 数量(属性)
  14. */
  15. public get Count() { return this._items.length; }
  16. /**
  17. * 添加
  18. * @param item Item
  19. */
  20. public Add(item: T): void {
  21. this._items.push(item);
  22. }
  23. /**
  24. * 移除
  25. * @param item Item
  26. * @returns 是否移除成功
  27. */
  28. public Remove(item: T): boolean {
  29. for (var i = 0, j = this._items.length; i < j; i++) {
  30. if (this._items[i] === item) {
  31. this._items.splice(i, 1);
  32. return true;
  33. }
  34. }
  35. return false;
  36. }
  37. /**
  38. * 从索引处移除
  39. * @param index 索引
  40. * @returns 是否移除成功
  41. */
  42. public RemoveAt(index: number): boolean {
  43. if (index < 0 || index >= this._items.length) {
  44. return false;
  45. }
  46. this._items.splice(index, 1);
  47. return true;
  48. }
  49. /**
  50. * 包含
  51. * @param item Item
  52. * @returns True: 包含; False: 未包含
  53. */
  54. public Contains(item: T): boolean {
  55. for (var i = 0, j = this._items.length; i < j; i++) {
  56. if (this._items[i] === item) {
  57. return true;
  58. }
  59. }
  60. return false;
  61. }
  62. /**
  63. * 排序
  64. * @param comparer 比较器
  65. */
  66. public Sort(comparer?: (a: T, b: T) => number): void {
  67. this._items.sort(comparer);
  68. }
  69. /**
  70. * 获取下标(不存在返回-1)
  71. * @param item Item
  72. * @returns 下标
  73. */
  74. public IndexOf(item: T): number {
  75. for (var i = 0, j = this._items.length; i < j; i++) {
  76. if (this._items[i] === item) {
  77. return i;
  78. }
  79. }
  80. return -1;
  81. }
  82. /**
  83. * 索引器
  84. * @param index 索引
  85. * @returns Item
  86. */
  87. public GetItem(index: number): T {
  88. return this._items[index];
  89. }
  90. /**
  91. * 迭代器
  92. * @param callback 回调
  93. */
  94. public Foreach(callback: (item: T, index: number) => void, thisArg?: any): void {
  95. if (callback) {
  96. this._items.forEach((value: T, index: number, _: T[]) => {
  97. callback.call(thisArg, value, index);
  98. });
  99. }
  100. }
  101. /**
  102. * 过滤
  103. * @param predicate
  104. * @returns 过滤后新的List<T>
  105. */
  106. public Filter(predicate: (value: T, index: number, array: T[]) => unknown): List<T> {
  107. return new List<T>(this._items.filter(predicate))
  108. }
  109. /**
  110. * 清理
  111. */
  112. public Clear() {
  113. this._items = [];
  114. }
  115. }