import chalk from 'chalk'; import deepmerge, { Options } from 'deepmerge'; export const ArrayMergeOverwrite: Options['arrayMerge'] = ( destinationArray, sourceArray, options, ) => sourceArray; export const ArrayMergeCombine: Options['arrayMerge'] = ( target, source, options, ) => { const destination = target.slice(); source.forEach((item, index) => { if (typeof destination[index] === 'undefined') { destination[index] = options?.cloneUnlessOtherwiseSpecified( item, options, ); } else if (options?.isMergeableObject(item)) { destination[index] = deepmerge(target[index], item, options); } else if (target.indexOf(item) === -1) { destination.push(item); } }); return destination; }; export const ArrayMergeCombineRespectKeyOrId: Options['arrayMerge'] = ( target, source, options, ) => { const destination = target.slice(); // TODO: Currently will throw misdirect error if sourceElem is string of array (i.e: TRACK_FOR_CHANGES, SOURCE_ID) source.forEach((sourceElem, sourceIdx) => { if (typeof sourceElem !== 'object') { console.log( chalk.bgYellowBright( "WARNING: DeepMergeHelper.ts > ArrayMergeCombineRespectKeyOrId(): sourceElem is not type 'object'", ) + ` - Source: ${JSON.stringify(source)} - Destination: ${JSON.stringify(destination)} - Merge behaviour: Overwrite --> Destination = Source `, ); destination[sourceIdx] = sourceElem; return; // continue } var uniqueAttr = 'key' in sourceElem ? 'key' : 'id'; const targetIndex = target.findIndex( (targetElem) => targetElem[uniqueAttr] === sourceElem[uniqueAttr], ); if (targetIndex !== -1) { // Merge objects if the 'key' matches destination[targetIndex] = deepmerge( target[targetIndex], sourceElem, options, ); } else { // Push new element if no matching 'key' is found destination.push(sourceElem); } }); return destination; };