Skip to content
This repository has been archived by the owner on Jan 23, 2021. It is now read-only.

fix: deep assign should ignore inseparable object #7

Closed
wants to merge 1 commit into from
Closed
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
14 changes: 13 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,18 @@ function toObject(val) {
return Object(val);
}

function isInseparableObj(val) {
if (val instanceof Date) {
return true;
}

if (val instanceof RegExp) {
return true;
}

return false;
}

function assignKey(to, from, key) {
var val = from[key];

Expand All @@ -24,7 +36,7 @@ function assignKey(to, from, key) {
}
}

if (!hasOwnProperty.call(to, key) || !isObj(val)) {
if (!hasOwnProperty.call(to, key) || !isObj(val) || isInseparableObj(to[key])) {
to[key] = val;
} else {
to[key] = assign(Object(to[key]), from[key]);
Expand Down
28 changes: 28 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,34 @@ test('support strings as targets', t => {
t.end();
});

test('support Date as targets', t => {
var target = fn({date: new Date()}, {date: 1446275964787});
t.is(target.date, 1446275964787);
t.is(target.date.constructor, Number);
t.end();
});

test('support Date as targets', t => {
var target = fn({date: new Date()}, {date: new Date(1446275964787)});
t.is(target.date.getTime(), 1446275964787);
t.is(target.date.constructor, Date);
t.end();
});

test('support RegExp as targets', t => {
var target = fn({regexp: /reg/}, {regexp: 'string'});
t.is(target.regexp.constructor, String);
t.is(target.regexp, 'string');
t.end();
});

test('support RegExp as targets', t => {
var target = fn({regexp: /reg/}, {regexp: /new/});
t.is(target.regexp.constructor, RegExp);
t.is(target.regexp.test('new'), true);
t.end();
});

test('support arrays as targets', t => {
var target = {a: ['many']};
var source = {a: []};
Expand Down