From 03a63cc37a97593009239151851243451f6dc111 Mon Sep 17 00:00:00 2001 From: Hafsteinn Date: Wed, 27 Jan 2021 17:13:54 +0100 Subject: [PATCH] #185 change customMerge signature to allow for ignoring null or empty string overwrites + a sweet little util function customMergeIgnoreEmptyValues for cuteness --- index.d.ts | 1 + index.js | 10 +++++++--- test/merge.js | 15 +++++++++++++++ 3 files changed, 23 insertions(+), 3 deletions(-) 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 033b8cf..cdf9cd7 100644 --- a/index.js +++ b/index.js @@ -14,12 +14,12 @@ const defaultArrayMerge = (target, source, options) => { .map(element => cloneUnlessOtherwiseSpecified(element, options)) } -const getMergeFunction = (key, options) => { +const getMergeFunction = (key, options, target, source) => { if (!options.customMerge) { return deepmerge } - const customMerge = options.customMerge(key) + const customMerge = options.customMerge(key, target, source) return typeof customMerge === `function` ? customMerge : deepmerge } @@ -61,7 +61,7 @@ const mergeObject = (target, source, options) => { } if (propertyIsOnObject(target, key) && options.isMergeable(source[key])) { - destination[key] = getMergeFunction(key, options)(target[key], source[key], options) + destination[key] = getMergeFunction(key, options, target[key], source[key])(target[key], source[key], options) } else { destination[key] = cloneUnlessOtherwiseSpecified(source[key], options) } @@ -114,4 +114,8 @@ deepmerge.all = (array, inputOptions) => { return array.reduce((prev, next) => deepmerge(prev, next, options)) } +deepmerge.customMergeIgnoreEmptyValues = (key, target, source) => !target || target === '' + ? () => source + : () => target; + module.exports = deepmerge diff --git a/test/merge.js b/test/merge.js index 789d2f8..2bcd068 100644 --- a/test/merge.js +++ b/test/merge.js @@ -677,6 +677,21 @@ test('Falsey properties should be mergeable', function(t) { 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(); +}) + test('should not mutate options', function(t) { var options = {}