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 d51d92d commit 03a63cc
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 @@ -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
}

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

Expand Down

0 comments on commit 03a63cc

Please sign in to comment.