-
Notifications
You must be signed in to change notification settings - Fork 41
/
clone.js
49 lines (38 loc) · 944 Bytes
/
clone.js
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
49
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
/**
* Create a deep copy of x which must be a legal JSON object/array/value
* @param {object|array|string|number|null} x object/array/value to clone
* @returns {object|array|string|number|null} clone of x
*/
module.exports = clone;
function clone(x) {
if(x == null || typeof x !== 'object') {
return x;
}
if (x instanceof String || x instanceof Number || x instanceof Boolean) {
return x.valueOf();
}
if(Array.isArray(x)) {
return cloneArray(x);
}
return cloneObject(x);
}
function cloneArray (x) {
var l = x.length;
var y = new Array(l);
for (var i = 0; i < l; ++i) {
y[i] = clone(x[i]);
}
return y;
}
function cloneObject (x) {
var keys = Object.keys(x);
var y = {};
for (var k, i = 0, l = keys.length; i < l; ++i) {
k = keys[i];
y[k] = clone(x[k]);
}
return y;
}