Skip to content

Commit

Permalink
Merge pull request #697 from cscott/master
Browse files Browse the repository at this point in the history
Deep-copy arrays with $.extend() (fixes gh bug #696)
  • Loading branch information
madrobby committed Feb 16, 2013
2 parents 27f798e + 9684402 commit 980a221
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/zepto.js
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,11 @@ var Zepto = (function() {

function extend(target, source, deep) {
for (key in source)
if (deep && isPlainObject(source[key])) {
if (!isPlainObject(target[key])) target[key] = {}
if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
if (isPlainObject(source[key]) && !isPlainObject(target[key]))
target[key] = {}
if (isArray(source[key]) && !isArray(target[key]))
target[key] = []
extend(target[key], source[key], deep)
}
else if (source[key] !== undefined) target[key] = source[key]
Expand Down
12 changes: 12 additions & 0 deletions test/zepto.html
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,18 @@ <h1>Zepto DOM unit tests</h1>
// can override DOM element
$.extend(true, obj, { element:{a:'b'} })
t.assertEqual('b', obj.element.a)

// deep copy with array
obj = {}
var initial = { array: [1,2,3,4], object:{a:{b:["c","d"]}} }
$.extend(true, obj, initial)
t.assertTrue($.isArray(obj.array))
t.assertEqual(JSON.stringify(obj), JSON.stringify(initial))
t.refuteIdentical(obj, initial)
t.refuteIdentical(obj.array, initial.array)
t.refuteIdentical(obj.object, initial.object)
t.refuteIdentical(obj.object.a, initial.object.a)
t.refuteIdentical(obj.object.a.b, initial.object.a.b)
},

testExtensionAPI: function(t) {
Expand Down

0 comments on commit 980a221

Please sign in to comment.