|
| 1 | +import { PrivateApiUsageDto } from './dto'; |
| 2 | + |
| 3 | +export type Group<Key, Value> = { |
| 4 | + key: Key; |
| 5 | + values: Value[]; |
| 6 | +}; |
| 7 | + |
| 8 | +export function grouped<Key, Value>( |
| 9 | + values: Value[], |
| 10 | + keyForValue: (value: Value) => Key, |
| 11 | + areKeysEqual: (key1: Key, key2: Key) => boolean, |
| 12 | +) { |
| 13 | + const result: Group<Key, Value>[] = []; |
| 14 | + |
| 15 | + for (const value of values) { |
| 16 | + const key = keyForValue(value); |
| 17 | + |
| 18 | + let existingGroup = result.find((group) => areKeysEqual(group.key, key)); |
| 19 | + |
| 20 | + if (existingGroup === undefined) { |
| 21 | + existingGroup = { key, values: [] }; |
| 22 | + result.push(existingGroup); |
| 23 | + } |
| 24 | + |
| 25 | + existingGroup.values.push(value); |
| 26 | + } |
| 27 | + |
| 28 | + return result; |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Makes sure that each private API is only listed once in a given context. |
| 33 | + */ |
| 34 | +function dedupeUsages<Key>(contextGroups: Group<Key, PrivateApiUsageDto>[]) { |
| 35 | + for (const contextGroup of contextGroups) { |
| 36 | + const newUsages: typeof contextGroup.values = []; |
| 37 | + |
| 38 | + for (const usage of contextGroup.values) { |
| 39 | + const existing = newUsages.find((otherUsage) => otherUsage.privateAPIIdentifier === usage.privateAPIIdentifier); |
| 40 | + if (existing === undefined) { |
| 41 | + newUsages.push(usage); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + contextGroup.values = newUsages; |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +export function groupedAndDeduped<Key>( |
| 50 | + usages: PrivateApiUsageDto[], |
| 51 | + keyForUsage: (usage: PrivateApiUsageDto) => Key, |
| 52 | + areKeysEqual: (key1: Key, key2: Key) => boolean, |
| 53 | +) { |
| 54 | + const result = grouped(usages, keyForUsage, areKeysEqual); |
| 55 | + dedupeUsages(result); |
| 56 | + return result; |
| 57 | +} |
| 58 | + |
| 59 | +/** |
| 60 | + * Return value is sorted in decreasing order of usage of a given private API identifer |
| 61 | + */ |
| 62 | +export function groupedAndSortedByPrivateAPIIdentifier<Key>( |
| 63 | + groupedByKey: Group<Key, PrivateApiUsageDto>[], |
| 64 | +): Group<string, Key>[] { |
| 65 | + const flattened = groupedByKey.flatMap((group) => group.values.map((value) => ({ key: group.key, value }))); |
| 66 | + |
| 67 | + const groupedByPrivateAPIIdentifier = grouped( |
| 68 | + flattened, |
| 69 | + (value) => value.value.privateAPIIdentifier, |
| 70 | + (id1, id2) => id1 === id2, |
| 71 | + ).map((group) => ({ key: group.key, values: group.values.map((value) => value.key) })); |
| 72 | + |
| 73 | + groupedByPrivateAPIIdentifier.sort((group1, group2) => group2.values.length - group1.values.length); |
| 74 | + |
| 75 | + return groupedByPrivateAPIIdentifier; |
| 76 | +} |
0 commit comments