(initialObj: T, mergeObj: T, levels = 2)
| 6 | * By default, this merges 2 levels deep. |
| 7 | */ |
| 8 | export function merge<T>(initialObj: T, mergeObj: T, levels = 2): T { |
| 9 | // If the merge value is not an object, or we have no merge levels left, |
| 10 | // we just set the value to the merge value |
| 11 | if (!mergeObj || typeof mergeObj !== 'object' || levels <= 0) { |
| 12 | return mergeObj; |
| 13 | } |
| 14 | |
| 15 | // If the merge object is an empty object, and the initial object is not undefined, we return the initial object |
| 16 | if (initialObj && Object.keys(mergeObj).length === 0) { |
| 17 | return initialObj; |
| 18 | } |
| 19 | |
| 20 | // Clone object |
| 21 | const output = { ...initialObj }; |
| 22 | |
| 23 | // Merge values into output, resursively |
| 24 | for (const key in mergeObj) { |
| 25 | if (Object.prototype.hasOwnProperty.call(mergeObj, key)) { |
| 26 | output[key] = merge(output[key], mergeObj[key], levels - 1); |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | return output; |
| 31 | } |
no test coverage detected