(target: AnyObject, source: AnyObject)
| 81 | type AnyObject = Record<string, any>; |
| 82 | |
| 83 | export function deepMergeObjects<T>(target: AnyObject, source: AnyObject): T { |
| 84 | const merged: AnyObject = {}; |
| 85 | // Include all keys from both objects |
| 86 | const allKeys = new Set([...Object.keys(target), ...Object.keys(source)]); |
| 87 | |
| 88 | allKeys.forEach((key) => { |
| 89 | const targetValue = target[key]; |
| 90 | const sourceValue = source[key]; |
| 91 | |
| 92 | if ( |
| 93 | (isNil(sourceValue) && !isNil(targetValue)) || |
| 94 | (sourceValue === '' && |
| 95 | typeof targetValue === 'string' && |
| 96 | targetValue !== '') |
| 97 | ) { |
| 98 | // Keep target value if source value is null or undefined |
| 99 | merged[key] = targetValue; |
| 100 | } else if ( |
| 101 | sourceValue !== undefined && |
| 102 | isObject(targetValue) && |
| 103 | isObject(sourceValue) |
| 104 | ) { |
| 105 | // Recursively merge objects |
| 106 | merged[key] = deepMergeObjects(targetValue, sourceValue); |
| 107 | } else if (sourceValue !== undefined) { |
| 108 | // Directly assign any non-undefined source values |
| 109 | merged[key] = sourceValue; |
| 110 | } else if (sourceValue === undefined && target[key] !== undefined) { |
| 111 | // Keep target value if source value is undefined |
| 112 | merged[key] = targetValue; |
| 113 | } |
| 114 | }); |
| 115 | |
| 116 | return merged as T; |
| 117 | } |
| 118 | |
| 119 | // Helper function to check if a value is an object (but not null or an array) |
| 120 | function isObject(value: any): boolean { |
no test coverage detected