Browser extension that demonstrates the Web Annotation Discovery mechanism: subscribe to people’s annotation collections/‘feeds’, to see their notes on the web; and create & publish annotations yourself.

web-annotation-discovery-we.../src/util/ unique.ts
35 lines
1.1 KiB

  1. /**
  2. * Return an array equal to the given one, but with duplicate items removed.
  3. * @param items The array to deduplicate. Not mutated.
  4. * @param getItemId Get the identifier to compare sameness of two items.
  5. * Defaults to the item itself, so sameness means strict equality
  6. * (`item1 === item2`).
  7. * @param merge Callback function to merge duplicate items if desired; the
  8. * returned value will take the place of the first item.
  9. * @returns A new array.
  10. */
  11. export function unique<T>(
  12. items: T[],
  13. getItemId: (item: T) => any = (item) => item,
  14. merge?: (item1: T, item2: T) => T,
  15. ): T[] {
  16. const seen = new Set();
  17. const newItems: T[] = [];
  18. for (const item of items) {
  19. const id = getItemId(item);
  20. if (id === undefined || !seen.has(id)) {
  21. newItems.push(item);
  22. seen.add(id);
  23. } else if (merge) {
  24. const indexOfConflictingItem = newItems.findIndex(
  25. (newItem) => getItemId(newItem) === id,
  26. );
  27. newItems[indexOfConflictingItem] = merge(
  28. newItems[indexOfConflictingItem],
  29. item,
  30. );
  31. }
  32. }
  33. return newItems;
  34. }