1
0
Fork 0

Added deep cloning for objects

closure/master
Mike Gerwitz 2011-01-09 01:46:46 -05:00
parent 49f10dfaee
commit aa1d38b007
2 changed files with 22 additions and 2 deletions

View File

@ -145,7 +145,10 @@ exports.clone = function clone( data, deep )
{ {
if ( hasOwn.call( data, prop ) ) if ( hasOwn.call( data, prop ) )
{ {
newobj[ prop ] = data[ prop ]; newobj[ prop ] = ( deep )
? clone( data[ prop ] )
: data[ prop ]
;
} }
} }

View File

@ -66,7 +66,10 @@ for ( prop in obj )
// //
// deep clone // deep clone
var deep_arr = [ [ 1, 2 ], [ 3, 4 ], [ 5, [ 6, 7 ] ], { a: 1 } ], var deep_arr = [ [ 1, 2 ], [ 3, 4 ], [ 5, [ 6, 7 ] ], { a: 1 } ],
deep_obj = { a: [ 1 ], b: [ 2 ], c: { d: 3 } },
deep_arr2 = util.clone( deep_arr, true ), deep_arr2 = util.clone( deep_arr, true ),
deep_obj2 = util.clone( deep_obj, true ),
deep_i = 0; deep_i = 0;
@ -77,6 +80,12 @@ assert.deepEqual(
"Deep cloned values are equal" "Deep cloned values are equal"
); );
assert.deepEqual(
deep_obj2,
deep_obj,
"Deep cloned values are equal"
);
deep_i = deep_arr.length; deep_i = deep_arr.length;
while ( deep_i-- ) while ( deep_i-- )
{ {
@ -86,3 +95,11 @@ while ( deep_i-- )
); );
} }
for ( prop in deep_obj )
{
assert.ok(
( deep_obj2[ prop ] !== deep_obj[ prop ] ),
"Deep cloned object's values are cloned (" + prop + ")"
);
}