52 lines
936 B
JavaScript
52 lines
936 B
JavaScript
|
'use strict';
|
||
|
|
||
|
/**
|
||
|
* Module dependenices
|
||
|
*/
|
||
|
|
||
|
var utils = require('./utils');
|
||
|
|
||
|
/**
|
||
|
* Recursively clone native types.
|
||
|
*/
|
||
|
|
||
|
function cloneDeep(val, instanceClone) {
|
||
|
switch (utils.typeOf(val)) {
|
||
|
case 'object':
|
||
|
return cloneObjectDeep(val, instanceClone);
|
||
|
case 'array':
|
||
|
return cloneArrayDeep(val, instanceClone);
|
||
|
default:
|
||
|
return utils.clone(val);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function cloneObjectDeep(obj, instanceClone) {
|
||
|
if (utils.isObject(obj)) {
|
||
|
var res = {};
|
||
|
utils.forOwn(obj, function(obj, key) {
|
||
|
this[key] = cloneDeep(obj, instanceClone);
|
||
|
}, res);
|
||
|
return res;
|
||
|
} else if (instanceClone) {
|
||
|
return instanceClone(obj);
|
||
|
} else {
|
||
|
return obj;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function cloneArrayDeep(arr, instanceClone) {
|
||
|
var len = arr.length, res = [];
|
||
|
var i = -1;
|
||
|
while (++i < len) {
|
||
|
res[i] = cloneDeep(arr[i], instanceClone);
|
||
|
}
|
||
|
return res;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Expose `cloneDeep`
|
||
|
*/
|
||
|
|
||
|
module.exports = cloneDeep;
|