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

Make it works for Array #11

Open
wants to merge 4 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
19 changes: 19 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,18 @@ function extend(target, obj) {
target[key] = val;
}
target[key] = assign(target[key] || {}, val);
} else if (isArray(val)) {
var array = [];
for (var i = 0; i < val.length; i++) {
if (isPrimitive(val[i])) {
array.push(val[i]);
} else {
array.push(assign({}, val[i]));
}

}
target[key] = array;

} else {
target[key] = val;
}
Expand All @@ -60,6 +72,13 @@ function isObject(obj) {
return typeOf(obj) === 'object' || typeOf(obj) === 'function';
}

/**
* Returns true if the object is an array.
*/
function isArray(obj) {

Choose a reason for hiding this comment

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

Wouldn't it be easier just to use Array.isArray?

Copy link

Choose a reason for hiding this comment

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

The author should be using the is-array package.

return typeOf(obj) === 'array';
}

/**
* Returns true if the given `key` is an own property of `obj`.
*/
Expand Down
25 changes: 24 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ describe('assign', function() {
var two = {e: 'f', g: ['h']};
assign(one, two);
assert.deepEqual(one.g, ['h']);
assert.equal(one.g, two.g);
assert.deepEqual(one.g, two.g);
assert.equal(typeof one, 'function');
});

Expand Down Expand Up @@ -322,5 +322,28 @@ describe('symbols', function() {
var res = assign(a, b);
assert.equal(res[key], 'xyz');
});

it('should deeply assign properties in an array:', function() {
var template = {
b: [
{

a: {
a: 0
}
}
]
};
var one = assign({}, template);
var two = assign({}, template);
one.b[0].a = {
b: 0
};
two.b[0].a = {
c: 0
};

assert.deepEqual(one.b[0].a, {b: 0});
});
}
});