deepClone.js
1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var clone = require('./clone');
var forOwn = require('../object/forOwn');
var kindOf = require('./kindOf');
var isPlainObject = require('./isPlainObject');
/**
* Recursively clone native types.
*/
function deepClone(val, instanceClone) {
switch ( kindOf(val) ) {
case 'Object':
return cloneObject(val, instanceClone);
case 'Array':
return cloneArray(val, instanceClone);
default:
return clone(val);
}
}
function cloneObject(source, instanceClone) {
if (isPlainObject(source)) {
var out = {};
forOwn(source, function(val, key) {
this[key] = deepClone(val, instanceClone);
}, out);
return out;
} else if (instanceClone) {
return instanceClone(source);
} else {
return source;
}
}
function cloneArray(arr, instanceClone) {
var out = [],
i = -1,
n = arr.length,
val;
while (++i < n) {
out[i] = deepClone(arr[i], instanceClone);
}
return out;
}
module.exports = deepClone;