UNPKG

@andranik-arakelyan/js-utilities

Version:
1 lines 1.97 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.deepMerge=deepMerge;function deepMerge(target,source,path){if(!target||typeof target!=="object"){throw new Error("Target must be an object")}if(!source||typeof source!=="object"){return target}if(path){const pathParts=path.split(".");let current=target;for(let i=0;i<pathParts.length-1;i++){const part=pathParts[i];if(!isNaN(Number(part))){const index=Number(part);if(!Array.isArray(current)){throw new Error(`Expected array at path segment '${pathParts.slice(0,i).join(".")}', but found ${typeof current}`)}if(index>=current.length){throw new Error(`Array index ${index} is out of bounds at path '${pathParts.slice(0,i+1).join(".")}'`)}current=current[index]}else{if(!current[part]||typeof current[part]!=="object"){current[part]={}}current=current[part]}}const finalPart=pathParts[pathParts.length-1];if(!isNaN(Number(finalPart))){const index=Number(finalPart);if(!Array.isArray(current)){throw new Error(`Expected array at path segment '${pathParts.slice(0,-1).join(".")}', but found ${typeof current}`)}if(index>=current.length){throw new Error(`Array index ${index} is out of bounds at path '${path}'`)}if(!current[index]||typeof current[index]!=="object"){current[index]={}}performDeepMerge(current[index],source)}else{if(!current[finalPart]||typeof current[finalPart]!=="object"){current[finalPart]={}}performDeepMerge(current[finalPart],source)}}else{performDeepMerge(target,source)}return target}function performDeepMerge(target,source){for(const key in source){if(source.hasOwnProperty(key)){const sourceValue=source[key];if(sourceValue===null||sourceValue===undefined){target[key]=sourceValue}else if(Array.isArray(sourceValue)){target[key]=[...sourceValue]}else if(typeof sourceValue==="object"&&sourceValue.constructor===Object&&target[key]&&typeof target[key]==="object"&&target[key].constructor===Object){performDeepMerge(target[key],sourceValue)}else{target[key]=sourceValue}}}}