-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathutils.js
73 lines (66 loc) · 2.13 KB
/
utils.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
module.exports = {
extendCircular: function(target, source, visited, data) {
visited = visited || [];
data = data || [];
var self = this;
if (!source || 'object' !== typeof source) return source;
if (source instanceof Date) return new Date(source.getTime());
if (source instanceof RegExp) return new RegExp(source);
if (source instanceof Array) {
return source.map(function(element) {
return self.extendCircular({}, element, visited, data);
})
}
var index = visited.indexOf(source);
if (!!~index) return data[index].$ref;
var target = source.constructor? new source.constructor() : {};
var idx = visited.push(source);
data[idx] = { $ref: target };
for (key in source) {
var value = source[key];
target[key] = self.extendCircular({}, value, visited, data);
}
return target;
},
extend: function(target, source) {
var self = this;
if (!source || 'object' !== typeof source) return source;
if (source instanceof Date) return new Date(source.getTime());
if (source instanceof RegExp) return new RegExp(source);
if (source instanceof Array) {
return source.map(function(element) {
return self.extend({}, element);
})
}
var target = source.constructor? new source.constructor() : {};
for (key in source) {
var value = source[key];
target[key] = self.extend({}, value);
}
return target;
},
shallowCopy: function(source, deep) {
if (source instanceof Array) {
var copy = [];
for (var i=0; i < source.length; i++) {
copy[i] = (deep)? this.shallowCopy(source[i], deep) : source[i];
}
return copy;
}else if (source instanceof Object) {
var copy = {};
for (var key in source) {
copy[key] = (deep)? this.shallowCopy(source[key], deep) : source[key];
}
return copy;
}else return source;
},
cloneCircular: function(source) {
return this.extendCircular({}, source);
},
clone: function(source) {
return this.extend({}, source);
},
cloneJSON: function(json) {
return JSON.parse(JSON.stringify(json));
}
}