From 396e0854acf9bdd84154d60bc7a4d2a30449dcfe Mon Sep 17 00:00:00 2001 From: Hafsteinn Date: Tue, 6 Oct 2020 12:34:30 +0200 Subject: [PATCH] #185 change customMerge signature to allow for ignoring null or empty string overwrites --- index.js | 22 +++++++++++----------- test/merge.js | 12 ++++++++++++ 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/index.js b/index.js index 0ac71be..f8d6af2 100644 --- a/index.js +++ b/index.js @@ -16,11 +16,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 } @@ -59,16 +59,16 @@ function mergeObject(target, source, options) { }) } getKeys(source).forEach(function(key) { - if (propertyIsUnsafe(target, key)) { - return + if (propertyIsUnsafe(target, key)) { + return + } + + if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { + destination[key] = getMergeFunction(key, options, target[key], source[key])(target[key], source[key], options); + } else + destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); } - - if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { - destination[key] = getMergeFunction(key, options)(target[key], source[key], options) - } else { - destination[key] = cloneUnlessOtherwiseSpecified(source[key], options) - } - }) + ); return destination } diff --git a/test/merge.js b/test/merge.js index fa2ac5b..662408e 100644 --- a/test/merge.js +++ b/test/merge.js @@ -667,3 +667,15 @@ 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: (key, target, source) => !target || target === '' ? () => source : () => target, + }); + + t.deepEqual(res, { someNewVariable: 'herp',very: {nested: { thing: 'derp'}} }) + t.end() +})