Dedupe.jsm 944 B

1234567891011121314151617181920212223242526272829303132333435
  1. this.Dedupe = class Dedupe {
  2. constructor(createKey) {
  3. this.createKey = createKey || this.defaultCreateKey;
  4. }
  5. defaultCreateKey(item) {
  6. return item;
  7. }
  8. /**
  9. * Dedupe any number of grouped elements favoring those from earlier groups.
  10. *
  11. * @param {Array} groups Contains an arbitrary number of arrays of elements.
  12. * @returns {Array} A matching array of each provided group deduped.
  13. */
  14. group(...groups) {
  15. const globalKeys = new Set();
  16. const result = [];
  17. for (const values of groups) {
  18. const valueMap = new Map();
  19. for (const value of values) {
  20. const key = this.createKey(value);
  21. if (!globalKeys.has(key) && !valueMap.has(key)) {
  22. valueMap.set(key, value);
  23. }
  24. }
  25. result.push(valueMap);
  26. valueMap.forEach((value, key) => globalKeys.add(key));
  27. }
  28. return result.map(m => Array.from(m.values()));
  29. }
  30. };
  31. const EXPORTED_SYMBOLS = ["Dedupe"];