( obj: Json | Json[], existingStore?: StringMapping, )
| 5 | export type StringMapping = { [key: string]: string }; |
| 6 | |
| 7 | export function removeIdsFromObjs( |
| 8 | obj: Json | Json[], |
| 9 | existingStore?: StringMapping, |
| 10 | ): { |
| 11 | cleanedObject: Json | Json[]; |
| 12 | idStore: StringMapping; |
| 13 | } { |
| 14 | /** |
| 15 | * Removes IDs (as defined by utils.isID) from an arbitrary JSON object. |
| 16 | * Replace IDs with an ID in the form ID1, ID2, etc. |
| 17 | * Returns the cleaned object and a lookup table (idStore) of the original IDs |
| 18 | * to the new IDs. |
| 19 | */ |
| 20 | const store: StringMapping = existingStore ?? {}; |
| 21 | // Deepcopy to prevent mutating the original object |
| 22 | const removedObj = JSON.parse(JSON.stringify(obj)); |
| 23 | // If already have an idStore, start counting from the last index |
| 24 | let idIdx = Object.entries(store).length; |
| 25 | |
| 26 | function findAndReplaceID(json: Json | Json[]) { |
| 27 | if (!json || typeof json !== "object") return; |
| 28 | |
| 29 | // Creates the same iterator for both arrays and objects |
| 30 | const entries = Array.isArray(json) |
| 31 | ? json.entries() |
| 32 | : Object.entries(json as { [key: string]: Json }); |
| 33 | |
| 34 | for (const [key, value] of entries) { |
| 35 | const k = key as string; |
| 36 | if (typeof value === "object") { |
| 37 | findAndReplaceID(value); |
| 38 | } else if (typeof value === "string") { |
| 39 | if (value.includes("/")) { |
| 40 | // If string is a path, operate on individual segments |
| 41 | const urlParts = value |
| 42 | .split("/") |
| 43 | .map((part) => (isID(part) ? getOrGenerateID(part) : part)); |
| 44 | (json as any)[k] = urlParts.join("/"); |
| 45 | } else if (isID(value)) { |
| 46 | (json as any)[k] = getOrGenerateID(value); |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | function getOrGenerateID(value: string): string { |
| 53 | let id = store[value]; |
| 54 | if (!id) { |
| 55 | id = `ID${++idIdx}`; |
| 56 | store[value] = id; |
| 57 | } |
| 58 | return id; |
| 59 | } |
| 60 | |
| 61 | findAndReplaceID(removedObj); |
| 62 | return { cleanedObject: removedObj, idStore: store }; |
| 63 | } |
| 64 |
no test coverage detected