Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. export type SetItemComparator<T> = (a: T, b: T) => boolean;
  2.  
  3. /**
  4. *
  5. */
  6. export class ComparableSet<T> {
  7. items: Array<T>;
  8. comparator: SetItemComparator<T>;
  9.  
  10. /**
  11. *
  12. * @param items
  13. * @param comparator
  14. */
  15. constructor(items: Array<T> = [], comparator?: SetItemComparator<T>) {
  16. this.items = items;
  17.  
  18. if (comparator) {
  19. this.comparator = comparator;
  20. } else {
  21. // Default comparator
  22. this.comparator = (a: T, b: T): boolean => a === b;
  23. }
  24. }
  25.  
  26. /**
  27. *
  28. * @param item
  29. */
  30. add(item: T): void {
  31. if (!this.has(item)) {
  32. this.items.push(item);
  33. }
  34. }
  35.  
  36. /**
  37. *
  38. * @param newSet
  39. */
  40. concat(newSet: ComparableSet<T>) {
  41. newSet.items.forEach(newItem => {
  42. this.add(newItem);
  43. });
  44. }
  45.  
  46. /**
  47. *
  48. */
  49. copy(): ComparableSet<T> {
  50. return new ComparableSet(this.items.slice(0), this.comparator);
  51. }
  52.  
  53. /**
  54. *
  55. * @param item
  56. */
  57. has(item: T): boolean {
  58. return this.items.find(setItem => this.comparator(item, setItem)) !== undefined;
  59. }
  60.  
  61. list(): Array<T> {
  62. return this.items.slice(0);
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement