Skip to content
Merged
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
20 changes: 15 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,21 @@ function deepmergeConstructor (options) {
}

for (i = 0, il = sourceKeys.length; i < il; ++i) {
isNotPrototypeKey(key = sourceKeys[i]) &&
(
(key in target && (targetKeys.indexOf(key) !== -1 && (result[key] = _deepmerge(target[key], source[key])), true)) ||
(result[key] = clone(source[key]))
)
if (!isNotPrototypeKey(key = sourceKeys[i])) {
continue
}

if (key in target) {
if (targetKeys.indexOf(key) !== -1) {
if (cloneProtoObject && isMergeableObject(source[key]) && Object.getPrototypeOf(source[key]) !== JSON_PROTO) {
result[key] = cloneProtoObject(source[key])
} else {
result[key] = _deepmerge(target[key], source[key])
}
}
} else {
result[key] = clone(source[key])
}
}
return result
}
Expand Down
23 changes: 23 additions & 0 deletions test/merge-proto-objects.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ const { Readable } = require('node:stream')
const deepmerge = require('../index')
const { test } = require('tape')

class Foo {
constructor (foo) {
this.foo = foo
}
}

test('merge nested objects should be immutable', function (t) {
t.plan(3)
const src = {
Expand Down Expand Up @@ -86,6 +92,23 @@ test('should not merge the buffers when cloned by reference', async t => {
t.same(result.logger.buffer, Buffer.of(1, 2, 3))
})

test('should clone by reference with proto object in both source and target', async t => {
t.plan(4)
const foo2 = new Foo(2)
const result = deepmerge({
cloneProtoObject (x) {
t.ok(x instanceof Foo)
return x
}
})(
{ foo: new Foo(1) },
{ foo: foo2 }
)
t.equal(typeof result.foo, 'object')
t.ok(result.foo instanceof Foo)
t.same(result.foo, foo2)
})

test('doc example', async t => {
const stream = process.stdout

Expand Down