Skip to content

Commit

Permalink
TehShrike#185 change customMerge signature to allow for ignoring null…
Browse files Browse the repository at this point in the history
… or empty string overwrites + a sweet little util function customMergeIgnoreEmptyValues for cuteness
  • Loading branch information
Hafsteinn-Ingason-Tidal committed Jan 27, 2021
1 parent dacb4bc commit b965118
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
1 change: 1 addition & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ declare namespace deepmerge {

export function all (objects: object[], options?: Options): object;
export function all<T> (objects: Partial<T>[], options?: Options): T;
export function customMergeIgnoreEmptyValues (key: any, target: any, source: any): any;
}

export = deepmerge;
10 changes: 7 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -106,4 +106,8 @@ deepmerge.all = function deepmergeAll(array, options) {
}, {})
}

deepmerge.customMergeIgnoreEmptyValues = (key, target, source) => !target || target === ''
? () => source
: () => target;

module.exports = deepmerge
15 changes: 15 additions & 0 deletions test/merge.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
})

0 comments on commit b965118

Please sign in to comment.