-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
49 lines (46 loc) · 1.13 KB
/
index.ts
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
/***
* 深克隆
*/
class DeepCloner {
private cache = []
clone(source) {
if (source instanceof Object) {
const cacheDist = this.getCache(source)
if (cacheDist) {
return cacheDist
} else {
let dist;
if (source instanceof Array) {
dist = new Array()
} else if (source instanceof Function) {
dist = function () {
return source.apply(this, arguments)
}
} else if (source instanceof Date) {
dist = new Date(source)
} else if (source instanceof RegExp) {
dist = new RegExp(source.source, source.flags)
} else {
dist = new Object()
}
this.cache.push([source, dist])
for (let key in source) {
if (source.hasOwnProperty(key)) {
dist[key] = this.clone(source[key])
}
}
return dist
}
}
return source
}
private getCache(source) {
for (let i = 0; i < this.cache.length; i++) {
if (this.cache[i][0] === source) {
return this.cache[i][1]
}
}
return undefined
}
}
export default DeepCloner