1 const isObject = (value: any): value is object =>
2 typeof value === "object" &&
3 value != null &&
4 !(value instanceof Boolean) &&
5 !(value instanceof Date) &&
6 !(value instanceof Number) &&
7 !(value instanceof RegExp) &&
8 !(value instanceof String)
9
10 const isPrimitive = (val) => {
11 return val !== Object(val)
12 }
13
14 function decycle(object: any, replacer?: Function | null) {
15 const objects = new WeakMap()
16
17 function deepCopy(value, path) {
18 let oldPath
19 let newObj
20
21 if (replacer != null) {
22 value = replacer(value)
23 }
24
25 if (isObject(value)) {
26 oldPath = objects.get(value)
27 if (oldPath !== undefined) {
28 return { $ref: oldPath }
29 }
30
31 objects.set(value, path)
32
33 if (Array.isArray(value)) {
34 newObj = []
35 value.forEach((el, idx) => {
36 newObj[idx] = deepCopy(el, path + "[" + idx + "]")
37 })
38 } else {
39 newObj = {}
40 Object.keys(value).forEach((name) => {
41 newObj[name] = deepCopy(
42 value[name],
43 path + "[" + JSON.stringify(name) + "]"
44 )
45 })
46 }
47 return newObj
48 }
49
50 return !isPrimitive(value) ? value + "" : value
51 }
52
53 return deepCopy(object, "$")
54 }
55
56 export function stringifyCircular(
57 object: any,
58 replacer?: Function | null,
59 space?: number
60 ): string {
61 return JSON.stringify(decycle(object, replacer), null, space)
62 }