/
index.js
52 lines (36 loc) · 993 Bytes
/
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
const clone = o => JSON.parse(JSON.stringify(o))
function deepClone (input) {
if (!(input instanceof Object)) return input
if (Array.isArray(input)) {
let iLen = input.length
const arr = new Array(iLen)
for (;iLen--;) {
arr[iLen] = deepClone(input[iLen])
}
return arr
}
const clObj = {}
for (const i in input) {
clObj[i] = deepClone(input[i])
}
return clObj
}
const safeClone = (input, history = []) => {
if (!(input instanceof Object)) return input
if (history.indexOf(input) > -1) return '[Circular]'
history.push(input)
if (Array.isArray(input)) {
let iLen = input.length
const arr = new Array(iLen)
for (;iLen--;) {
arr[iLen] = safeClone(input[iLen], history)
}
return arr
}
const ret = {}
for (const i in input) {
ret[i] = (input[i] instanceof Object) ? safeClone(input[i], history) : input[i]
}
return ret
}
module.exports = { clone, realClone: safeClone, safeClone, deepClone }