-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathImplementJSONstringify().js
More file actions
54 lines (54 loc) · 1.24 KB
/
ImplementJSONstringify().js
File metadata and controls
54 lines (54 loc) · 1.24 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
function stringify(data) {
if(typeof data === 'bigint') {
throw new Error('Do not know how to serialize a BigInt at JSON.stringify');
}
if(typeof data === 'string') {
return `"${data}"`;
}
if(typeof data === 'function') {
return undefined;
}
if(data !== data) {
return "null";
}
if(data === Infinity) {
return "null";
}
if(data === -Infinity) {
return "null";
}
if(typeof data === 'number') {
return `${data}`;
}
if(typeof data === 'boolean') {
return `${data}`;
}
if(data === null) {
return "null";
}
if(data === undefined) {
return 'null';
}
if(typeof data === 'symbol') {
return 'null';
}
if(data instanceof Date) {
return `"${data.toISOString()}"`;
}
if(Array.isArray(data)) {
let dd = data.map((d)=> stringify(d) )
let a = `[${dd.join(',')}]`
return a
}
if(typeof data == 'object')
{
let arr = Object.entries(data).reduce((ar, [key, value])=>{
if(value === undefined)
return ar
ar.push(`"${key}":${stringify(value)}`)//recursion to find the string form of nested object
return ar
},[])
let ans = `{${arr.join(',')}}`//using join to add commas between strings of the object entries
return ans
}
}