1
0
Fork 0

Added deep cloning for arrays

closure/master
Mike Gerwitz 2011-01-09 01:38:40 -05:00
parent 13fae953fd
commit 0f905481bf
2 changed files with 45 additions and 4 deletions

View File

@ -108,16 +108,33 @@ exports.defineSecureProp = getDefineSecureProp();
* Clones an object * Clones an object
* *
* @param {Object} data object to clone * @param {Object} data object to clone
* @param {boolean} deep perform deep clone (defaults to shallow)
* *
* @return {Object} cloned object * @return {Object} cloned object
*/ */
exports.clone = function( data ) exports.clone = function clone( data, deep )
{ {
deep = !!deep;
if ( data instanceof Array ) if ( data instanceof Array )
{
if ( !deep )
{ {
// return a copy of the array // return a copy of the array
return data.slice( 0 ); return data.slice( 0 );
} }
// if we're performing a deep clone, we have to loop through each of the
// elements of the array and clone them
var ret = [];
for ( var i = 0, len = data.length; i < len; i++ )
{
// clone this element
ret.push( clone( data[ i ], deep ) );
}
return ret;
}
else if ( data instanceof Object ) else if ( data instanceof Object )
{ {
var newobj = {}, var newobj = {},

View File

@ -62,3 +62,27 @@ for ( prop in obj )
); );
} }
//
// deep clone
var deep_arr = [ [ 1, 2 ], [ 3, 4 ], [ 5, [ 6, 7 ] ], { a: 1 } ],
deep_arr2 = util.clone( deep_arr, true ),
deep_i = 0;
// ensure that the cloned values still match
assert.deepEqual(
deep_arr2,
deep_arr,
"Deep cloned values are equal"
);
deep_i = deep_arr.length;
while ( deep_i-- )
{
assert.ok(
( deep_arr2[ i ] !== deep_arr[ i ] ),
"Deep cloned array's values are cloned"
);
}