Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply clone option to target object #209

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ function emptyTarget(val) {
return Array.isArray(val) ? [] : {}
}

function firstArrayEntry(arr) {
return arr && arr.length ? arr[0] : []
}

function cloneUnlessOtherwiseSpecified(value, options) {
return (options.clone !== false && options.isMergeableObject(value))
? deepmerge(emptyTarget(value), value, options)
Expand Down Expand Up @@ -51,8 +55,21 @@ function propertyIsUnsafe(target, key) {
&& Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.
}

// Retrieves either a new object or the appropriate target object to mutate.
function getDestinationObject(target, source, options) {
const targetDefined = typeof target !== 'undefined'
const isArray = Array.isArray(target) || Array.isArray(source)
const doMerge = options && (options.mergeWithTarget || options.clone === false)

if (targetDefined && doMerge) {
return Array.isArray(target) ? firstArrayEntry(target) : target
}

return isArray ? [] : {};
Copy link

@RebeccaStevens RebeccaStevens Nov 12, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The destination object should never be an array.

This is how I would define this function:

function getDestinationObject(target, options) {
	const targetDefined = typeof target !== 'undefined'
	const doMerge = options && (options.mergeWithTarget || options.clone === false)

	if (targetDefined && doMerge) {
		return target
	}

	return {};
}

Call from deepmergeAll

Copy link
Author

@creativeux creativeux Nov 12, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For me, the array check was required because during recursion it's possible that there is a property being handled whose value is undefined, but we know that the source value is an array, so we need to instantiate an empty object that can be merged into. If I remove this, nested properties with array types will fail to merge because an array source will try to be merged into an object target.

Copy link

@RebeccaStevens RebeccaStevens Nov 13, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah sorry, I was thrown off by the function mergeObject's name. I assumed that it's parameters were always non-array objects but in actual fact it merges any 2 values (or returns the latter one if they can't be merged).

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wait no, that's not right. mergeObject does only ever receive non-array objects. target and source should never be arrays in mergeObject - arrays should be handled by options.arrayMerge.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@creativeux I suspect you'll need to update the logic in deepmerge itself to handle the case of target being undefined.

https://github.com/TehShrike/deepmerge/blob/master/index.js#L87-L93

}

function mergeObject(target, source, options) {
var destination = {}
var destination = getDestinationObject(target, source, options)
if (options.isMergeableObject(target)) {
getKeys(target).forEach(function(key) {
destination[key] = cloneUnlessOtherwiseSpecified(target[key], options)
Expand Down Expand Up @@ -100,7 +117,7 @@ deepmerge.all = function deepmergeAll(array, options) {

return array.reduce(function(prev, next) {
return deepmerge(prev, next, options)
}, {})
}, getDestinationObject(array, undefined, options))
Copy link

@RebeccaStevens RebeccaStevens Nov 12, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Following on from my other comment, this is how getDestinationObject would be called from deepmergeAll:

const target = array[0];
const destination = getDestinationObject(target, options)
const source = destination === target ? array.slice(1) : array

return source.reduce(function(prev, next) {
	return deepmerge(prev, next, options)
}, destination)

}

module.exports = deepmerge
57 changes: 57 additions & 0 deletions test/merge.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,63 @@
var merge = require('../')
var test = require('tape')

test('should handle an undefined value in the target object when merging', function(t) {
var src = { key1: 'value1', key2: { key4: 'value4'}, key3: ['value3'], key5: undefined }
var target = { key1: 'value', key2: undefined, key3: undefined, key5: ['value5'], key6: ['value6'], key7: { key8: 'value8'} }

var notClonedRes = merge(target, src, {mergeWithTarget: true})

// Undefined target
t.assert(notClonedRes.key2 === target.key2, 'should merge object source into undefined value');
t.assert(notClonedRes.key3 === target.key3, 'should merge array source into undefined target');
t.assert(typeof notClonedRes.key2 === 'object', 'should retain object type when merging into undefined target');
t.assert(Array.isArray(notClonedRes.key3), 'should retain array type when merging into undefined target');

// Explicit undefined source
t.assert(typeof key5 === 'undefined', 'should overwrite target value with explicitly undefined source value');

// Not defined source props
t.assert(Array.isArray(notClonedRes.key6), 'should preserve target property value when no source value exists');
t.assert(typeof notClonedRes.key7 === 'object', 'should preserve target property value when no source value exists');
t.end()
})

test('result should retain target type information when mergeWithTarget set to true', function(t) {
var src = { key1: 'value1', key2: 'value2' }
class CustomType {}
var target = new CustomType()

var res = merge(target, src, {mergeWithTarget: true})
t.not(src instanceof CustomType)
t.assert(target instanceof CustomType)
t.assert(res instanceof CustomType)
t.end()
})

test('modify target object if mergeWithTarget set to true', function(t) {
var src = { key1: 'value1', key2: 'value2' }
var target = { key3: 'value3'}

var clonedRes = merge(target, src)
var notClonedRes = merge(target, src, {mergeWithTarget: true})

t.assert(clonedRes !== target, 'result should be cloned')
t.assert(notClonedRes === target, 'result should maintain target reference')
t.end()
})

test('merge.all mutates target object when mergeWithTarget set to true', function(t) {
var src = { key1: 'value1', key2: 'value2' }
var target = { key3: 'value3'}

var clonedRes = merge.all([target, src])
var notClonedRes = merge.all([target, src], {mergeWithTarget: true})

t.assert(clonedRes !== target, 'result should be cloned')
t.assert(notClonedRes === target, 'result should maintain first array entry reference')
t.end()
})

test('add keys in target that do not exist at the root', function(t) {
var src = { key1: 'value1', key2: 'value2' }
var target = {}
Expand Down