|
| 1 | +import { DiffRecord, TranslationValue } from '../../types'; |
| 2 | + |
| 3 | +type DiffValue = string | undefined; |
| 4 | +type DiffObject = { [key: string]: DiffValue | DiffObject }; |
| 5 | + |
1 | 6 | /** |
2 | 7 | * Transform nested JS object to key-value pairs using dot notation. |
| 8 | + * Handles undefined values from diff operations (representing deletions). |
3 | 9 | */ |
4 | | -export const dotObject = (obj: object): Record<string, string> => { |
5 | | - const res: Record<string, string> = {}; |
| 10 | +export const dotObject = (obj: TranslationValue | DiffObject): DiffRecord => { |
| 11 | + const res: DiffRecord = {}; |
6 | 12 |
|
7 | | - function recurse(obj: object, keyPrefix?: string) { |
8 | | - for (const key in obj) { |
9 | | - const value = obj[key as keyof typeof obj]; |
| 13 | + function recurse(current: TranslationValue | DiffObject, keyPrefix?: string) { |
| 14 | + for (const key of Object.keys(current)) { |
| 15 | + const value = current[key]; |
10 | 16 | const newKey = keyPrefix ? `${keyPrefix}.${key}` : key; |
11 | | - if (value && typeof value === 'object') { |
| 17 | + if (value !== undefined && typeof value === 'object') { |
12 | 18 | // it's a nested object, so do it again |
13 | 19 | recurse(value, newKey); |
14 | 20 | } else { |
15 | | - // it's not an object, so set the property |
| 21 | + // it's a string or undefined (deletion marker) |
| 22 | + res[newKey] = value; |
| 23 | + } |
| 24 | + } |
| 25 | + } |
| 26 | + recurse(obj); |
| 27 | + return res; |
| 28 | +}; |
| 29 | + |
| 30 | +/** |
| 31 | + * Transform nested JS object to key-value pairs using dot notation. |
| 32 | + * Use this version when you know the input contains only strings (no diff undefined values). |
| 33 | + */ |
| 34 | +export const flattenTranslations = (obj: TranslationValue): Record<string, string> => { |
| 35 | + const res: Record<string, string> = {}; |
| 36 | + |
| 37 | + function recurse(current: TranslationValue, keyPrefix?: string) { |
| 38 | + for (const key of Object.keys(current)) { |
| 39 | + const value = current[key]; |
| 40 | + if (value === undefined) continue; |
| 41 | + const newKey = keyPrefix ? `${keyPrefix}.${key}` : key; |
| 42 | + if (typeof value === 'object') { |
| 43 | + recurse(value, newKey); |
| 44 | + } else { |
16 | 45 | res[newKey] = value; |
17 | 46 | } |
18 | 47 | } |
|
0 commit comments