CollectionUtil.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import Dictionary from "typescript-collections/dist/lib/Dictionary";
  2. export class CollectionUtil {
  3. public static contains2(array: any[], object: any): boolean {
  4. for (let i: number = 0; i < array.length; i++) {
  5. if (array[i] === object) {
  6. return true;
  7. }
  8. }
  9. return false;
  10. }
  11. public static last(array: any[]): any {
  12. return array[array.length - 1];
  13. }
  14. /**
  15. * Iterates through a dictionary and calls iterationFunction.
  16. * If iterationFunction returns true the key gets stored.
  17. * all stored key will finally be removed from the dictionary.
  18. * @param dict
  19. * @param iterationFunction
  20. */
  21. public static removeDictElementIfTrue<T, V>(dict: Dictionary<T, V>, iterationFunction: (key: T, value: V) => boolean): void {
  22. let toDeleteEntries: T[] = [];
  23. dict.forEach(function (key: T, value: V): void {
  24. let shallDelete: boolean = iterationFunction(key, value);
  25. if (shallDelete) {
  26. toDeleteEntries.push(key);
  27. }
  28. });
  29. for (let i: number = 0; i < toDeleteEntries.length; i++) {
  30. dict.remove(toDeleteEntries[i]);
  31. }
  32. }
  33. public static getLastElement<T>(array: T[]): T {
  34. return array[array.length - 1];
  35. }
  36. public static binarySearch<T>(array: T[],
  37. element: T,
  38. cmp: (elem1: T, elem2: T) => number,
  39. startIndex: number = 0,
  40. endIndex: number = array.length): number {
  41. let mid: number = 1;
  42. while (startIndex < endIndex) {
  43. mid = Math.floor((startIndex + endIndex) / 2);
  44. let c: number = cmp(array[mid], element);
  45. if (c === 0) {
  46. return mid;
  47. }
  48. if (c < 0) {
  49. startIndex = mid + 1;
  50. }
  51. if (0 < c) {
  52. endIndex = mid;
  53. }
  54. }
  55. return -mid;
  56. }
  57. }