CollectionUtil.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import { Dictionary } from "typescript-collections";
  2. declare global {
  3. interface Array<T> {
  4. /** Returns the last element from an array */
  5. last(): T;
  6. /** Deletes all elements from an array */
  7. clear(): void;
  8. /** Returns true if the element is found in the array */
  9. contains(elem: T): boolean;
  10. }
  11. }
  12. if (!Array.prototype.last) {
  13. Array.prototype.last = function<T>(): T {
  14. return this[this.length - 1];
  15. };
  16. }
  17. if (!Array.prototype.clear) {
  18. Array.prototype.clear = function<T>(): void {
  19. this.length = 0;
  20. };
  21. }
  22. if (!Array.prototype.contains) {
  23. Array.prototype.contains = function<T>(elem: T): boolean {
  24. return this.indexOf(elem) !== -1;
  25. };
  26. }
  27. /**
  28. * This class implements static methods to perform useful operations on lists, dictionaries, ...
  29. */
  30. export class CollectionUtil {
  31. public static contains2(array: any[], object: any): boolean {
  32. for (let i: number = 0; i < array.length; i++) {
  33. if (array[i] === object) {
  34. return true;
  35. }
  36. }
  37. return false;
  38. }
  39. public static last(array: any[]): any {
  40. return array[array.length - 1];
  41. }
  42. /**
  43. * Iterates through a dictionary and calls iterationFunction.
  44. * If iterationFunction returns true the key gets stored.
  45. * all stored key will finally be removed from the dictionary.
  46. * @param dict
  47. * @param iterationFunction
  48. */
  49. public static removeDictElementIfTrue<S, T, V>(thisPointer: S, dict: Dictionary<T, V>,
  50. iterationFunction: (thisPointer: S, key: T, value: V) => boolean): void {
  51. const toDeleteEntries: T[] = [];
  52. dict.forEach(function (key: T, value: V): void {
  53. const shallDelete: boolean = iterationFunction(thisPointer, key, value);
  54. if (shallDelete) {
  55. toDeleteEntries.push(key);
  56. }
  57. });
  58. for (let i: number = 0; i < toDeleteEntries.length; i++) {
  59. dict.remove(toDeleteEntries[i]);
  60. }
  61. }
  62. public static getLastElement<T>(array: T[]): T {
  63. return array[array.length - 1];
  64. }
  65. public static binarySearch<T>(array: T[],
  66. element: T,
  67. cmp: (elem1: T, elem2: T) => number,
  68. startIndex: number = 0,
  69. endIndex: number = array.length - 1): number {
  70. let mid: number = 1;
  71. while (startIndex < endIndex) {
  72. mid = Math.floor((startIndex + endIndex) / 2);
  73. const c: number = cmp(array[mid], element);
  74. if (c === 0) {
  75. return mid;
  76. }
  77. if (c < 0) {
  78. startIndex = mid + 1;
  79. }
  80. if (0 < c) {
  81. endIndex = mid;
  82. }
  83. }
  84. return -mid;
  85. }
  86. }