-
Notifications
You must be signed in to change notification settings - Fork 1
/
Json_Stringify.js
109 lines (98 loc) · 2.41 KB
/
Json_Stringify.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
* @param {any} data
* @return {string}
*/
function stringify(data) {
if (data === null) return 'null';
if (typeof data === 'number') {
// Handle NaN and Infinity
if (isNaN(data) || !isFinite(data)) {
return 'null';
}
return data.toString();
}
if (typeof data === 'boolean') {
return data.toString();
}
if (typeof data === 'string') {
return `"${data}"`;
}
if (typeof data === 'undefined' || typeof data === 'function' || typeof data === 'symbol') {
return undefined; // These types are omitted in objects
}
if (data instanceof Date) {
// Serialize Date objects as ISO strings
return `"${data.toISOString()}"`;
}
if (typeof data === 'bigint') {
// Serialize BigInt values as strings (JSON.stringify does not support BigInt)
throw new Error('BigInt');
}
if (Array.isArray(data)) {
const arrayContents = data.map((element) => stringify(element) || 'null');
return `[${arrayContents.join(',')}]`;
}
if (typeof data === 'object') {
const keyValuePairs = Object.keys(data)
.map((key) => {
const value = stringify(data[key]);
return value !== undefined ? `"${key}":${value}` : undefined;
})
.filter((pair) => pair !== undefined);
return `{${keyValuePairs.join(',')}}`;
}
return 'null';
}
const removeCycle = (obj) => {
//set store
const set = new WeakSet([obj]);
//recursively detects and deletes the object references
const iterateObj = (obj) => {
for (let key in obj) {
// if the key is not present in prototype chain
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === "object") {
// if the set has object reference
// then delete it
if (set.has(obj[key])) {
delete obj[key];
} else {
//store the object reference
set.add(obj[key]);
//recursively iterate the next objects
iterateObj(obj[key]);
}
}
}
}
};
iterateObj(obj);
};
let obj1 = {
a: 1,
b: {
c: 2,
d: -3,
e: {
f: {
g: -4,
},
},
h: {
i: 5,
j: 6,
},
},
};
console.log(stringify(obj1));
const List = function (val) {
this.next = null;
this.val = val;
};
const item1 = new List(10);
const item2 = new List(20);
const item3 = new List(30);
item1.next = item2;
item2.next = item3;
item3.next = item1;
console.log(stringify(item1));