forked from quasarframework/quasar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclone.js
More file actions
55 lines (46 loc) · 1.33 KB
/
clone.js
File metadata and controls
55 lines (46 loc) · 1.33 KB
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
// adapted from https://stackoverflow.com/a/40294058
export default function cloneDeep (data, hash = new WeakMap()) {
if (Object(data) !== data) return data
if (hash.has(data)) return hash.get(data)
const result = data instanceof Date
? new Date(data)
: (data instanceof RegExp
? new RegExp(data.source, data.flags)
: (data instanceof Set
? new Set()
: (data instanceof Map
? new Map()
: (typeof data.constructor !== 'function'
? Object.create(null)
: (data.prototype !== void 0 && typeof data.prototype.constructor === 'function'
? data
: new data.constructor()
)
)
)
)
)
if (typeof data.constructor === 'function' && typeof data.valueOf === 'function') {
const val = data.valueOf()
if (Object(val) !== val) {
const result = new data.constructor(val)
hash.set(data, result)
return result
}
}
hash.set(data, result)
if (data instanceof Set) {
data.forEach(val => {
result.add(cloneDeep(val, hash))
})
}
else if (data instanceof Map) {
data.forEach((val, key) => {
result.set(key, cloneDeep(val, hash))
})
}
return Object.assign(
result,
...Object.keys(data).map(key => ({ [key]: cloneDeep(data[key], hash) }))
)
}