forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert-object-to-json-string.ts
46 lines (44 loc) · 1.1 KB
/
convert-object-to-json-string.ts
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
// Time: O(n)
// Space: O(h)
// dfs
function jsonStringify(object: any): string {
let result = [];
let dfs = (object) => {
if (object === null) {
result.push('null');
return;
}
if (typeof object === 'number' || typeof object === 'boolean') {
result.push(String(object));
return;
}
if (typeof object === 'string') {
result.push(`"${object}"`);
return;
}
if (Array.isArray(object)) {
result.push('[');
for (const x of object) {
dfs(x);
result.push(',');
}
if (object.length) {
result.pop();
}
result.push(']');
return;
}
result.push('{');
for (const key in object) {
result.push(`"${key}":`)
dfs(object[key]);
result.push(',');
}
if (Object.keys(object).length) {
result.pop();
}
result.push('}');
}
dfs(object);
return result.join('');
};