-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
72 lines (54 loc) · 1.29 KB
/
index.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"use strict";
function getDataType(data) {
return Object.prototype.toString.call(data).slice(8, -1);
}
function isCyclic(data) {
let seenObjects = [];
function detect(data) {
if (data && getDataType(data) === "Object") {
if (seenObjects.indexOf(data) !== -1) {
return true;
}
seenObjects.push(data);
for (var key in data) {
if (data.hasOwnProperty(key) === true && detect(data[key])) {
return true;
}
}
}
return false;
}
return detect(data);
}
const deepClone = function(data) {
if (data === null || data === undefined) {
return undefined;
}
const dataType = getDataType(data);
if (dataType === "Date") {
let clonedDate = new Date();
clonedDate.setTime(data.getTime());
return clonedDate;
}
if (dataType === "Object") {
if (isCyclic(data) === true) {
return data;
}
let copiedObject = {};
// Iterate over the objects keys
for (let key in data) {
copiedObject[key] = deepClone(data[key]);
}
return copiedObject;
}
if (dataType === "Array") {
let copiedArray = [];
for (var i = 0; i < data.length; i++) {
copiedArray.push(deepClone(data[i]));
}
return copiedArray;
} else {
return data;
}
};
module.exports = deepClone;