Dedupe.sys.mjs (1104B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this file, 3 * You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 export class Dedupe { 6 constructor(createKey) { 7 this.createKey = createKey || this.defaultCreateKey; 8 } 9 10 defaultCreateKey(item) { 11 return item; 12 } 13 14 /** 15 * Dedupe any number of grouped elements favoring those from earlier groups. 16 * 17 * @param {Array} groups Contains an arbitrary number of arrays of elements. 18 * @returns {Array} A matching array of each provided group deduped. 19 */ 20 group(...groups) { 21 const globalKeys = new Set(); 22 const result = []; 23 for (const values of groups) { 24 const valueMap = new Map(); 25 for (const value of values) { 26 const key = this.createKey(value); 27 if (!globalKeys.has(key) && !valueMap.has(key)) { 28 valueMap.set(key, value); 29 } 30 } 31 result.push(valueMap); 32 valueMap.forEach((value, key) => globalKeys.add(key)); 33 } 34 return result.map(m => Array.from(m.values())); 35 } 36 }