This repository has been archived by the owner on Jun 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
128 lines (94 loc) · 2.5 KB
/
app.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
var easyCloner = module.exports = function(source) {
var
queue = [],
depth = 0;
queue.add = function(element) {
depth ++;
queue.push(element);
};
queue.remove = function(element) {
depth --;
queue.pop(element);
};
var cloner = function(source) {
// In case of a date
if (source instanceof Date) {
return new Date(source.getTime());
}
// In case of a Buffer
if (source instanceof Buffer) {
return new Buffer(source);
}
// In case of a function
if (typeof source === 'function') {
// Init function copy
var fun = function temporary() {
return source.apply(source.this, source.arguments);
};
// In case of a circular
if (depth !== 0 && queue.indexOf(source) !== -1) {
return '[circular]';
}
// Add properties
for (var propKey in this) {
if (source.hasOwnProperty(propKey)) {
if (typeof source[propKey] === 'object') {
queue.add(source);
fun[propKey] = cloner(source[propKey]);
queue.remove();
} else {
fun[propKey] = source[propKey];
}
}
}
// Return the function copy
return fun;
}
// In case of an array
if (Array.isArray(source)) {
// Init array copy
var array = [];
if (depth !== 0 && queue.indexOf(source) !== -1) {
return '[circular]';
}
// Fill the copy
for (var i = 0; i < source.length; i++) {
if (typeof source[i] === 'object') {
queue.add(source);
array[i] = cloner(source[i]);
queue.remove();
} else {
array[i] = source[i];
}
}
// Return the copy
return array;
}
// In case of an object
if (typeof source === 'object') {
// Init object copy
var obj = {};
// Avoid the circle for the circle is long and full of terrors
if (depth !== 0 && queue.indexOf(source) !== -1) {
return '[circular]';
} else {
queue.add(source);
}
// Fill the object copy
for (var key in source) {
if (typeof source[key] === 'object') {
queue.add(source);
obj[key] = cloner(source[key]);
queue.remove();
} else {
obj[key] = source[key];
}
}
// Return the object copy
return obj;
}
// Return the source because it's a primitive type
return source;
};
return cloner(source);
};