diff --git a/index.d.ts b/index.d.ts index 20f645a..13ec1d3 100644 --- a/index.d.ts +++ b/index.d.ts @@ -11,6 +11,7 @@ declare namespace deepmerge { export function all (objects: object[], options?: Options): object; export function all (objects: Partial[], options?: Options): T; + export function customMergeIgnoreEmptyValues (key: any, target: any, source: any): any; } export = deepmerge; diff --git a/index.js b/index.js index 761c002..142a37d 100644 --- a/index.js +++ b/index.js @@ -19,11 +19,11 @@ function defaultArrayMerge(target, source, options) { }) } -function getMergeFunction(key, options) { +function getMergeFunction(key, options, target, source) { if (!options.customMerge) { return deepmerge } - var customMerge = options.customMerge(key) + var customMerge = options.customMerge(key, target, source); return typeof customMerge === 'function' ? customMerge : deepmerge } @@ -69,7 +69,7 @@ function mergeObject(target, source, options) { if (!options.isMergeable(source[key]) || !propertyIsOnObject(target, key)) { destination[key] = cloneUnlessOtherwiseSpecified(source[key], options) } else { - destination[key] = getMergeFunction(key, options)(target[key], source[key], options) + destination[key] = getMergeFunction(key, options, target[key], source[key])(target[key], source[key], options) } }) return destination @@ -106,4 +106,8 @@ deepmerge.all = function deepmergeAll(array, options) { }, {}) } +deepmerge.customMergeIgnoreEmptyValues = (key, target, source) => !target || target === '' + ? () => source + : () => target; + module.exports = deepmerge diff --git a/test/merge.js b/test/merge.js index 1a99b28..e38c06e 100644 --- a/test/merge.js +++ b/test/merge.js @@ -676,3 +676,18 @@ test('Falsey properties should be mergeable', function(t) { t.ok(customMergeWasCalled, 'custom merge function was called') t.end() }) + +test('customMerge without overwriting with null or empty string', function(t) { + var src = { someNewVariable: "herp", very: { nested: { thing: "" } } }; + var target = { very: { nested: { thing: "derp" } } }; + + var res = merge(target, src, { + customMerge: merge.customMergeIgnoreEmptyValues, + }); + + t.deepEqual(res, { + someNewVariable: "herp", + very: { nested: { thing: "derp" } }, + }); + t.end(); +})